如何将 RFC 3339 中的日期转换为 javascript 日期对象(自 1970 年以来的毫秒数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11318634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert date in RFC 3339 to the javascript date object(milliseconds since 1970)
提问by DoTheEvo
Google calendar throws at me rfc3339, but all my dates are in those milliseconds since jan 1970.
谷歌日历向我抛出 rfc3339,但我所有的日期都是自 1970 年 1 月以来的毫秒数。
rfc3999:
RFC3999:
2012-07-04T18:10:00.000+09:00
javascript current time: (new Date()).getTime():
javascript 当前时间: (new Date()).getTime():
1341346502585
I prefer the the milliseconds because I only deal in countdowns and not in dates.
我更喜欢毫秒,因为我只处理倒计时而不是日期。
回答by Ry-
Datetimes in that format, with 3 decimal places and a “T”, have well-defined behaviourwhen passed to Date.parse
or the Date
constructor:
这种格式的日期时间,带有 3 个小数位和一个“T”,在传递给或构造函数时具有明确定义的行为:Date.parse
Date
console.log(Date.parse('2012-07-04T18:10:00.000+09:00'));
// 1341393000000 on all conforming engines
You have to be careful to always provide inputs that conform to the JavaScript specification, though, or you might unknowingly be falling back on implementation-defined parsing, which, being implementation-defined, isn't reliable across browsers and environments. For those other formats, there are options like manual parsing with regular expressions:
但是,您必须小心始终提供符合 JavaScript 规范的输入,否则您可能会在不知不觉中退回到实现定义的解析,而实现定义的解析在浏览器和环境中并不可靠。对于那些其他格式,有一些选项,例如使用正则表达式手动解析:
var googleDate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})([+-]\d{2}):(\d{2})$/;
function parseGoogleDate(d) {
var m = googleDate.exec(d);
var year = +m[1];
var month = +m[2];
var day = +m[3];
var hour = +m[4];
var minute = +m[5];
var second = +m[6];
var msec = +m[7];
var tzHour = +m[8];
var tzMin = +m[9];
var tzOffset = tzHour * 60 + tzMin;
return Date.UTC(year, month - 1, day, hour, minute - tzOffset, second, msec);
}
console.log(parseGoogleDate('2012-07-04T18:10:00.000+09:00'));
or full-featured libraries like Moment.js.
或者像Moment.js这样的全功能库。
回答by Spudley
There are two Javascript date libraries that you could try:
您可以尝试两个 Javascript 日期库:
Both of these will give you functions that allow you to parse and generate dates in pretty much any format.
这两者都会为您提供允许您解析和生成几乎任何格式的日期的函数。
If you're working with dates a lot, you'll want to use use one of these libraries; it's a whole lot less hassle than rolling your own functions every time.
如果您经常处理日期,则需要使用这些库之一;这比每次都滚动自己的功能要少得多。
Hope that helps.
希望有帮助。