使用JavaScript来解析时间 [英] Use JavaScript to Parse Time
问题描述
这可能是一件容易的事情,但我有点困惑如何做到这一点。如何使用JavaScript解析以下 ISO 8601 日期字符串的时间:
This is probably something easy, but I'm a bit confused how to do this. How can I, using JavaScript, parse only the time from the following ISO 8601 date string:
2009-12-06T17:10:00
换句话说,使用上面的字符串,我想输出:
In other words, with the string above, I'd like to output:
5:10 PM
任何有关这方面的指导/教程都会很棒。
Any guidance/tutorials on this would be great.
推荐答案
Chrome& Firefox:标准JavaScript日期构造函数采用ISO 8601日期字符串。例如:
Chrome & Firefox: Standard JavaScript Date constructor takes ISO 8601 date string. For example:
var sampleDate = new Date(2010-03-07T02:13:46Z);
返回此Date对象:Sun Mar 07 2010 13:13:46 GMT + 1100(AUS Eastern Daylight Time)
Returns this Date object: "Sun Mar 07 2010 13:13:46 GMT+1100 (AUS Eastern Daylight Time)"
这不适用于IE(包括最新的IE 9)
This does not work in IE (including latest IE 9)
这是Paul Sowden在 http://delete.me.uk/2005/03/iso8601.html :
Here is a cross-browser solution by Paul Sowden at http://delete.me.uk/2005/03/iso8601.html :
Date.prototype.setISO8601 = function (string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
}
用法:
var date = new Date();
date.setISO8601("2005-03-26T19:51:34Z");
如果您在JavaScript中执行了大量的datetime操作,我还可以建议检查一些JS库 MomentJS 。它处理一些常见的事情,如日期解析,格式化和计算两个日期之间的差异,并支持多个本地化。
If you do a lot of datetime manipulation in JavaScript, I can also suggest to check some JS libraries like MomentJS. It handles some common things like date parsing, formatting and calculating difference between two dates and has support for multiple localizations.
这篇关于使用JavaScript来解析时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!