【发布时间】:2019-03-15 05:39:40
【问题描述】:
我使用Date() 函数将MySQL Date 转换为JS Date 对象。
以下是我如何做的代码:
var a = "2019-03-12 12:30:03"; //MySQL Date
function MySQLToDate(dateString) {
if (typeof dateString === 'string') {
return new Date(dateString);
}
else {
return dateString; //in case the argument is already an object
}
}
alert(MySQLToDate(a));
//iOS Output: Invalid Date
//Normal Output: Tue Mar 12 2019 12:30:03 GMT+0530 (India Standard Time)
在我在 iPad 浏览器中对其进行测试之前,它完全可以正常工作。
它在 iOS 中返回 Invalid Date。当然,使用Date() 的原型函数如getDate()、getMonth() 等返回Nan。
所以为了克服这种情况,我进行了研究,在其中一个答案中,我发现将 MySQL 日期直接传递给 JS Date 函数是一种错误的做法。 [Source]
现在我的代码如下所示:
var a = "2019-03-12 12:30:03"; //MySQL Date
function MySQLToDate(dateString) {
if (typeof dateString === 'string') {
return new Date(dateString.replace(" ","T"));
}
else {
return dateString; //in case the argument is already an object
}
}
alert(MySQLToDate(a));
//iOS Output: Tue Mar 12 2019 18:00:03 GMT+0530 (India Standard Time)
//Normal Output: Tue Mar 12 2019 12:30:03 GMT+0530 (India Standard Time)
此解决方案没有给出无效日期错误,而是给出了一个无效日期。
我还尝试拆分 MySQL 日期并将年、月、日、小时、分钟、秒传递到 Date(),但对象中的时间仍然错误。
欢迎您的回答。
【问题讨论】:
-
@RK_15 这与我在我的问题中给出的答案(接受的)相同的问题。这个答案会给你一个错误的日期时间而不是一个无效的日期。
-
"2019-03-12 12:30:03" 不是 ECMA-262 支持的格式,因此解析取决于实现。 Apple 浏览器通常会返回无效日期。 "2019-03-12T12:30:03" 应该被解析为本地,但 Apple 浏览器将其解析为 UTC。手动解析的时候记得把月份减1。
标签: javascript ios date