From another answer on Stackoverflow is a conversion from Javascript date to .net DateTime:
long msSinceEpoch = 1260402952906; // Value from Date.getTime() in JavaScript return new DateTime(1970, 1, 1) + new TimeSpan(msSinceEpoch * 10000);
But how to do the reverse? DateTime to Javascript Date?
To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.
The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.
const d = new Date("2015/03/25"); The behavior of "DD-MM-YYYY" is also undefined. Some browsers will try to guess the format. Some will return NaN.
now() The static Date. now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
Try:
return DateTime.Now.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds
Edit: true UTC is better, but then we need to be consistent
return DateTime.UtcNow .Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc)) .TotalMilliseconds;
Although, on second thoughts it does not matter, as long as both dates are in the same time zone.
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); } }
JavaScript Usage:
var dt = new Date(<%= DateTime.Today.ToJavaScriptMilliseconds() %>); alert(dt);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With