Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime JavaScript vs C#

Tags:

javascript

c#

Regardless of many posts I've read the magic still in my code. I have DateTime value in db ('2011-03-30 00:00:00.000') that I retrieve for asp.net/mvc page where some javascript needs to read it and compare. The magic in the following:

<% 
DateTime unixTimeOffset = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DateTime testDate = new DateTime(2011,03,30,0,0,0,0);
%>
<%= (testDate - unixTimeOffset).TotalMilliseconds %>
...

Last string of the code gives me this value: 1301443200000 When I try to read it in JavaScript I have:

val myDate = new Date(1301443200000);

And myDate is Tue Mar 29 2011 20:00:00 GMT-0400 (Eastern Daylight Time) {} But not a March 30th as it should be.

I understand it provides date referencing to local time, GMT-4 but what is the solution to get it independent? Any ideas? Thanks.

like image 589
Maxim Avatar asked Jan 21 '23 03:01

Maxim


1 Answers

For C# Related Dates:

You may want to consider using DateTime.ToUniversalTime() and .UTCNow(), which will allow you to keep all days independent of time-zones.

 DateTime date = DateTime.UTCNow();

For Javascript-Related Dates:

Javascript features a UTC Method that should get you the Universal Time as well.

//Declaration
var date = new Date(Date.UTC(YYYY,MM,DD));

//Use
var newDate = date.toUTCString();

Hope this helps :)

like image 170
Rion Williams Avatar answered Jan 24 '23 01:01

Rion Williams