Converting Date to JS Date Object

I have a date in a weird format and I am not sure how to turn it into a JS Date Object. I am sure libraries like moment.js have utilities for this but I don't really want to load an entire library just for this conversion. Here is the data:

/Date(1472586116588-0400)/

EDIT: I have updated the back end code to use a string in the JSON instead of a C# Date time and then I convert the DateTime as follows:

Date.ToString("s");

This is giving me this string: 2016-09-02T10:13:12

So now my problem is if I do var date = new Date("2016-09-02T10:13:12"); javascript gives back:

Fri Sep 02 2016 06:13:12 GMT-0400 (EDT)

But it should give me:

Fri Sep 02 2016 10:13:12 GMT-0400 (EDT)

It appears the time zone conversion is being like doubled or something? Anyone know how to fix this?


我假设这是自时代以来的毫秒,用hhmm抵消,所以我会这样做:

var input = "/Date(1472586116588-0400)/";
var [match, msec, offset] = input.match(/((d+)([+-]d+))/);
var offsetHours = Math.floor(offset / 100);
var offsetMinutes = offset - offsetHours * 100;
var date = new Date(msec - offsetHours * 60 * 60 * 1000 - offsetMinutes * 60 * 1000);

console.log(date);

Fixed by changing backend data to string in ISO 8601 formate instead of C# DateTime as follows:

date.ToString("o");

This can then simply be turned into a javascript date using new Date({string here});

Credit to James Thorpe for suggesting fixing JSON data on backend rather than hacking it to fit on the front end.

链接地址: http://www.djcxy.com/p/18646.html

上一篇: 如何在JavaScript中输出ISO 8601格式的字符串?

下一篇: 将日期转换为JS日期对象