DateTime JavaScript vs C #

Regardless of many posts, I read the magic in my code. I have a DateTime value in db ('2011-03-30 00: 00: 00.000') that I am retrieving for an asp.net/mvc page where some javascript needs to be read and compared. The magic is as follows:

<% 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 %> ... 

The last line of code gives me this value: 1301443200000 When I try to read it in JavaScript, I have:

 val myDate = new Date(1301443200000); 

And myDate tue March 29, 2011 20:00:00 GMT-0400 (Eastern Daylight Time) {} But it should not be March 30, as it should be.

I understand that it provides a date that refers to local time, GMT-4, but what is the solution to gain independence? Any ideas? Thank you

+4
source share
3 answers

Your code is correct. The variable myDate contains the correct date, since Tue Mar 29 2011 20:00:00 GMT-0400 is the same point in time as Wed Mar 30 2011 00:00:00 GMT+0000 . I assume that you see the first, as this is the time zone of your computers. Use myDate.toUTCString() to see the date as UTC.

+1
source

For C # Related Dates:

You might want to use DateTime.ToUniversalTime () and . UTCNow () , which allows you to save all days regardless of time zones.

  DateTime date = DateTime.UTCNow(); 

For Javascript related dates:

Javascript has a UTC Method , which should also get you universal time.

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

Hope this helps :)

+6
source

Get the timezone offset in the client and add it to the value from the server. Like this:

 var serverOffset = 1301443200000; var localOffset = myDate.getTimezoneOffset() * 60 * 1000; var myDate = new Date(serverOffset + localOffset); console.log(myDate); // Wed Mar 30 2011 00:00:00 

Please note that Tue Mar 29 2011 20:00:00 GMT-0400 (Eastern Daylight Time) is the same point in time as your original UTC date. This method creates a new date that represents a new point in time. However, if you are just trying to display the same date value, then this method does the trick.

Alternatively, you can use Date UTC methods to print the original date in UTC:

 function pad(num) { return ("0" + num).slice(-2); } function formatDate(d) { return [d.getUTCFullYear(), pad(d.getUTCMonth() + 1), pad(d.getUTCDate())].join("-") + "T" + [pad(d.getUTCHours()), pad(d.getUTCMinutes()), pad(d.getUTCSeconds())].join(":") + "Z"; } formatDate(new Date(1301443200000)); 

Output:

 "2011-03-30T00:00:00Z" 
+2
source

Source: https://habr.com/ru/post/1345609/


All Articles