解析为毫秒更改日期

Parsing to milliseconds changes date

我在解析从服务器获取的 json 中的日期时遇到问题。日期格式为"YYYY-MM-dd HH-mm-ss CST"(时区在末尾),这是第一个条目:

2015-01-06 00:00:00 CST

我正在使用 Highcharts 绘制数据,我需要将其解析为毫秒,以便在 x 轴(日期时间)中正确使用。我对 javascript 中的日期转换不是很熟悉,所以我总是得到奇怪的结果(以毫秒为单位的解析值总是错误的,因此在不正确的点绘制图表)。

//obj['Time'] has the time value received = "2015-01-06 00:00:00 CST"

var fecha=obj['Time'].split(" ")[0].split("-"),
    hora=obj['Time'].split(" ")[1].split(":")[0];

var from = Date.parse( new Date(fecha[0], fecha[1], fecha[2], hora) );

所以,我尝试了以下方法:1) 直接解析 obj['Time']。 2) 使用 "manual splitting of the input date" 中的显式值创建一个新的日期对象(存储在 'from' 变量中)并解析它。

console.log("Original: " + obj['Time'] );
console.log("1) " + Date.parse(obj['Time']));
console.log("2) " + from);

console.log("Response 1: " + new Date( Date.parse(obj['Time']) ) );
console.log("Response 2: " + new Date( from ) );

这些是结果:

Original: 2015-01-06 00:00:00 CST
1) 1420524000000
2) 1423177200000

Response 1: Tue Jan 06 2015 07:00:00 GMT+0100 (CET)
Response 2: Fri Feb 06 2015 00:00:00 GMT+0100 (CET)    

我相信 new Date() 正在使用我的本地时区并进行转换,因为该值有 1 小时的偏移量 (GMT+0100 ???).. .所以所有东西都有一个不应该出现的"offset"。也许有人可以提醒我解析这个的正确方法是什么 :)

谢谢!

注意:我不需要在图表中显示时区,我只需要有正确的日期时间值。

此外,我知道在创建新的 Date 对象时月份的索引为 0,这就是它显示二月而不是一月的原因,但该修复仍然不正确

var date = "2015-01-06 00:00:00 CST".replace(/-/g, "/");
var orgDate = new Date(date);
var dateParsed = Date.parse(orgDate); //parse to timestamp. (In milliseconds)

document.write("Timestamp CST: " + dateParsed);
document.write("<br />");
document.write("<br />"); 
var dateToUTC = new Date(dateParsed);

document.write("UTC/GMT: " + dateToUTC.toUTCString());
document.write("<br />");
document.write("Local: " + dateToUTC.toString());
var timeStringUTC = Date.parse(new Date(dateToUTC.toUTCString()));
document.write("<br />"); 
document.write("<br />"); 

var UTCthen = orgDate.getUTCFullYear()+"-"+(parseInt(orgDate.getUTCMonth())+1 < 10 ? "0"+(parseInt(orgDate.getUTCMonth())+1) : orgDate.getUTCMonth()+1) + "-" + (orgDate.getUTCDate() < 10 ? "0"+orgDate.getUTCDate() : orgDate.getUTCDate())+"T00:00:00.000Z"
document.write("Timestamp UTC: " + Date.parse(UTCthen) );
document.write("<br />");   
document.write("Difference (milliseconds): " + (dateParsed - Date.parse(UTCthen)) + " // = 6 hours");  //6 hours

不通过分割解析。只需将破折号替换为 /。这将使它成为 Date.parse 的有效日期。正如您在代码片段中看到的那样。日期在 CST 时间发送,转换为 UTC 显示实际上是 伦敦[=] 早上六点。该示例还显示了两者之间的毫秒差异。我将解析的日期转换回它的原始 UTC 时间戳。这是在这一行中完成的:

 var UTCthen = orgDate.getUTCFullYear()+"-"+(parseInt(orgDate.getUTCMonth())+1 < 10 ? "0"+(parseInt(orgDate.getUTCMonth())+1) : orgDate.getUTCMonth()+1) + "-" + (orgDate.getUTCDate() < 10 ? "0"+orgDate.getUTCDate() : orgDate.getUTCDate())+"T00:00:00.000Z";

此行返回 UTC 日期并在其后追加时间 "T00:00:00.000Z" 强制 Date.parse 认为这是一个使用 Z(祖鲁语)的 ISO 字符串 GMT/UTC时间.

因此,在 UTCthen 上使用 Date.parse 应该可以得到标准化版本的时间戳。