Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime to javascript date

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?

like image 645
AJ. Avatar asked Mar 08 '10 19:03

AJ.


People also ask

How do I convert datetime to date?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.

What is new date () in JavaScript?

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.

How do I format a date in JavaScript?

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.

Is JavaScript date now UTC?

now() The static Date. now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.


2 Answers

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.

like image 184
AxelEckenberger Avatar answered Oct 05 '22 09:10

AxelEckenberger


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); 
like image 45
Yair Nevet Avatar answered Oct 05 '22 09:10

Yair Nevet