问题描述
我正在创建一个如下所示的日期时间字符串:2010-07-15 11:54:21
I am creating a datetime string that looks like this: 2010-07-15 11:54:21
使用以下代码,我在 Firefox 中得到无效日期,但在 Chrome 中运行良好
And with the following code I get invalid date in Firefox but works just fine in Chrome
var todayDateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds;
var date1 = new Date(todayDateTime);
在 firefox 中 date1 给了我一个无效的日期,但在 chrome 中它工作得很好,主要原因是什么?
In firefox date1 is giving me an invalid date, but in chrome its working just fine what would the main cause be?
推荐答案
您无法以任何方式实例化日期对象.它必须以特定的方式.以下是一些有效示例:
You can't instantiate a date object any way you want. It has to be in a specific way. Here are some valid examples:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
或
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
Chrome 必须更加灵活.
Chrome must just be more flexible.
来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
来自 apsillers 评论:
EMCAScript 规范只需要一种日期格式(即 YYYY-MM-DDTHH:mm:ss.sssZ)但是 实现可以自由支持自定义日期格式:如果字符串不符合 [ECMAScript 定义的] 格式,该函数可能会退回到任何特定于实现的启发式或实现-特定的日期格式." Chrome 和 FF 只是具有不同的特定于实现的日期格式."
the EMCAScript specification requires exactly one date format (i.e., YYYY-MM-DDTHH:mm:ss.sssZ) but custom date formats may be freely supported by an implementation: "If the String does not conform to that [ECMAScript-defined] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats." Chrome and FF simply have different "implementation-specific date formats."
这篇关于new Date() 在 Chrome 中运行,但在 Firefox 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!