Javascript的日期是在iOS无效 [英] Javascript date is invalid on iOS
问题描述
我工作的一个PhoneGap的基础iOS应用程序,这是已经为Android做的。以下线路工作正常,为Android,但并不适用于iOS。为什么呢?
I'm working on a Phonegap-based iOS app, which is already done for Android. The following lines are working fine for Android but not for iOS. Why?
var d = new Date("2015-12-31 00:00:00");
console.log(d.getDate() + '. ' + d.getMonth() + ' ' + d.getFullYear();
结果为Android:
Result for Android:
31.11 2015
结果在iOS上:
Result on iOS:
NaN. NaN NaN
在哪里差哪里来的?
Where is the difference coming from?
推荐答案
您的日期字符串是不是在指定的格式与新日期
工作。在规范的唯一格式是 ISO-8601的简化版本一>,但这只是添加ES5等支持可能的触摸而归。您的字符串不是这种格式,但它非常接近。
Your date string is not in a format specified to work with new Date
. The only format in the spec is a simplified version of ISO-8601, but that was only added in ES5 and so support may be touch and go. Your string isn't in that format, but it's really close.
如果您更改空间为 T
,你会在规格:
If you change the space to a T
, you'll be in spec:
var dateString = "2015-12-31 00:00:00";
var d = new Date(dateString.replace(' ', 'T'));
(我假设你没有真正使用一个字符串,因此替换
电话。)
请注意,有是在ES5规范,它是在ES2015(ES6)更正一个错误:当有一个在字符串中没有时区的指标会发生什么。在ISO-8601,无指示的意思是本地时间,但ES5规范说,则默认为以Z
(GMT)。他们固定在ES2015规范,但不幸的是一些JavaScript引擎遵循了ES5规范和其他人遵循ISO-8601(现在ES2015),因此对于固态跨浏览器支持,你需要包括一个时区的指标,否则你不知道它是否会PTED为GMT或当地时间间$ P $。你允许使用以Z
为GMT或 +/-
然后按 HH:MM
来GIE偏移。 (如 CST
缩写是不允许的,因为没有标准,它们。)
Note that there was an error in the ES5 specification which was corrected in ES2015 (ES6): What happens when there's no timezone indicator on the string. In ISO-8601, no indicator means "local time," but the ES5 specification said that it defaults to Z
(GMT). They fixed it in the ES2015 specification, but unfortunately some JavaScript engines followed the ES5 specification and others followed ISO-8601 (and now ES2015), so for solid cross-browser support, you need to include a timezone indicator because otherwise you don't know whether it will be interpreted as GMT or local time. You're allowed to use Z
for GMT or +/-
followed by HH:MM
to gie an offset. (Abbreviations like CST
are not allowed, as there's no standard for them.)
如果他们不支持然而,即使它没有证件,还有附近的普遍支持YYYY / MM / DD HH:MM:SS
。所以:
If they don't support that yet, even though it's undocumented, there's near universal support for YYYY/MM/DD HH:MM:SS
. So:
var dateString = "2015-12-31 00:00:00";
var d = new Date(dateString.replace(/-/g, '/'));
这篇关于Javascript的日期是在iOS无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!