DateTime to javascript date

前端 未结 10 1463
忘掉有多难
忘掉有多难 2020-11-28 05:40

From another answer on Stackoverflow is a conversion from Javascript date to .net DateTime:

long msSinceEpoch = 1260402952906; // Value from Date.getTime() i         


        
10条回答
  •  温柔的废话
    2020-11-28 06:09

    I know this is a little late, but here's the solution I had to come up with for handling dates when you want to be timezone independent. Essentially it involves converting everything to UTC.

    From Javascript to Server:

    Send out dates as epoch values with the timezone offset removed.

    var d = new Date(2015,0,1) // Jan 1, 2015
    // Ajax Request to server ...
    $.ajax({
      url: '/target',
      params: { date: d.getTime() - (d.getTimezoneOffset() * 60 * 1000) }
    });
    

    The server then recieves 1420070400000 as the date epoch.

    On the Server side, convert that epoch value to a datetime object:

    DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(epoch);
    

    At this point the date is just the date/time provided by the user as they provided it. Effectively it is UTC.

    Going the other way:

    When the server pulls data from the database, presumably in UTC, get the difference as an epoch (making sure that both date objects are either local or UTC):

    long ms = (long)utcDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
    

    or

    long ms = (long)localDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).TotalMilliseconds;
    

    When javascript receives this value, create a new date object. However, this date object is going to be assumed local time, so you need to offset it by the current timezone:

    var epochValue = 1420070400000 // value pulled from server.
    var utcDateVal = new Date(epochValue);
    var actualDate = new Date(utcDateVal.getTime() + (utcDateVal.getTimezoneOffset() * 60 * 1000))
    
    console.log(utcDateVal); // Wed Dec 31 2014 19:00:00 GMT-0500 (Eastern Standard Time)
    console.log(actualDate); // Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)
    

    As far as I know, this should work for any time zone where you need to display dates that are timezone independent.

提交回复
热议问题