DateTime to javascript date

AJ. picture AJ. · Mar 8, 2010 · Viewed 116.9k times · Source

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?

Answer

AxelEckenberger picture AxelEckenberger · Mar 8, 2010

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.