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);
Just what I needed
Thanks!
Very useful! Thanks!
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 %>);
Great . This help me a lot ! works with MVC5
var timeNew = @DateTimeJavaScript.ToJavaScriptMilliseconds(ViewBag.DateEnd) ;
var endDate = new Date(timeNew );
I knew it was the epoch! No suggestions of that on StackOverflow.
Thanks, saved me some time …