Converting .Net DateTime to JavaScript Date

JavaScript Date constructor accepts number of milliseconds since Unix epoch (1 January 1970 00:00:00 UTC). Here’s C# extension method that converts .Net DateTime object to JavaScript date:

public static class DateTimeJavaScript
{
   private static readonly long DatetimeMinTimeTicks =
      (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;

   public static long ToJavaScriptMilliseconds(this DateTime dt)
   {
      return (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
   }
}

Usage:

var dt = new Date(<%= DateTime.Today.ToJavaScriptMilliseconds() %>);
alert(dt);

Reference

Java System.currentTimeMillis() equivalent in C#

5 thoughts on “Converting .Net DateTime to JavaScript Date

  1. Thanks .. good solution but felt bit confusing at first glance

    I used it like below way in my aspx page ..


    jsDate = new Date(<%= DateTime.Now.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds %>);

  2. Great . This help me a lot ! works with MVC5

    var timeNew = @DateTimeJavaScript.ToJavaScriptMilliseconds(ViewBag.DateEnd) ;
    var endDate = new Date(timeNew );

  3. I knew it was the epoch! No suggestions of that on StackOverflow.
    Thanks, saved me some time …

Leave a Reply

Your email address will not be published. Required fields are marked *