Safari Javascript Date()NaN问题(yyyy-MM-dd HH:mm:ss) [英] Safari Javascript Date() NaN Issue (yyyy-MM-dd HH:mm:ss)
问题描述
我的代码在Google Chrome中正常运行,但在Safari中无效。
My code is working properly in Google Chrome, but not in Safari.
我发现我需要转换 yyyy-MM- dd HH:mm:ss
到 ISO 8601
,但我没有找到解决办法。
I figured out that I need to convert yyyy-MM-dd HH:mm:ss
to ISO 8601
, but I didn't found a solution to do this.
在线测试链接: http://jsfiddle.net/UVgHR/
Javascript:
Javascript:
$(document).ready(function() {
calculateMinutes();
setInterval(calculateMinutes, 60000);
});
function calculateMinutes() {
$('.calculateMinutes').each(function () {
var diff = Math.abs(new Date( $(this).data('timestamp') ) - new Date());
var minutes = Math.floor((diff/1000)/60);
$(this).html( minutes + ' min.' );
});
}
HTML示例:
<span class="calculateMinutes" data-timestamp="2014-02-18 15:00:48">
推荐答案
为了使您的问题更轻松,您的问题在于:
To make your question easier your problem is with:
new Date('2014-02-18 15:00:48')
这项工作在chrome中没有问题,但在safari中没有。 mdn谈到 ECMAScript 5 ISO-8601格式支持说:
This work okay in chrome but not in safari. The mdn talks about ECMAScript 5 ISO-8601 format support says:
或者,日期/时间字符串可以是ISO 8601格式。对于
示例,可以传递和解析2011-10-10(仅限日期)或2011-10-10T14:48:00(日期和
时间)。
Alternatively, the date/time string may be in ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed.
如果你包含 T
它可以工作:
If you include T
it works:
new Date('2014-02-18T15:00:48')
您可以使用新日期('2014-02-18T15:00:48'.replace(/ \ s /,'T'))
。
如果您处理了很多这样的案例,我建议您使用 时刻 无论有没有T,它都可以很好地处理这种情况:从字符串中解析。另外,你的整个例子更容易使用momentjs:
If you handle a lot of cases like this I will recommend using moment which seems to handle this case very well with or without T: parsing from string. Additionally your whole example is easier with momentjs:
var minutes = moment().diff("2014-02-18 15:00:48", 'minutes');
这篇关于Safari Javascript Date()NaN问题(yyyy-MM-dd HH:mm:ss)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!