alert(new Date('2010-11-29'));

Chrome, ff在这方面没有问题,但safari会喊“无效日期”。为什么?

编辑:好的,根据下面的评论,我使用了字符串解析,并尝试了这个:

alert(new Date('11-29-2010')); //doesn't work in safari
alert(new Date('29-11-2010')); //doesn't work in safari
alert(new Date('2010-29-11')); //doesn't work in safari

编辑2018年3月22日:似乎人们仍然在这里着陆-今天,我会使用moment或date-fns,然后就不用了。Date-fns是非常痛苦的,而且很轻。


当前回答

这不是最好的解决方案,尽管我只是捕获错误并返回当前日期。我个人觉得不解决Safari的问题,如果用户想要使用一个该死的不符合标准的浏览器——他们就得忍受这些怪癖。

function safeDate(dateString = "") {
  let date = new Date();
  try {
    if (Date.parse(dateString)) {
      date = new Date(Date.parse(dateString))
    }
  } catch (error) {
    // do nothing.
  }
  return date;
}

我建议让你的后端发送ISO日期。

其他回答

我用矩来解决这个问题。 例如

var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();

在我的情况下,它不是格式,这是因为在我的后端Node.js模型中,我将数据库变量定义为字符串而不是日期。

我的后端节点数据库模型说:

starttime:{
  type: String,
}

而不是正确的:

 starttime:{
    type: Date,
  }

要让解决方案在大多数浏览器上都能工作,您应该使用这种格式创建日期对象

(year, month, date, hours, minutes, seconds, ms)

例如:

dateObj = new Date(2014, 6, 25); //UTC time / Months are mapped from 0 to 11
alert(dateObj.getTime()); //gives back timestamp in ms

工作良好的IE, FF, Chrome和Safari。甚至是更老的版本。

IE开发中心:日期对象(JavaScript)

Mozilla Dev Network:日期

将字符串转换为日期格式(你必须知道服务器时区)

new Date('2015-06-16 11:00:00'.replace(/\s+/g, 'T').concat('.000+08:00')).getTime()  

where +08:00 =时区从服务器

最好的方法是使用以下格式:

new Date(year, month, day, hours, minutes, seconds, milliseconds)
var d = new Date(2018, 11, 24, 10, 33, 30, 0);

这在所有浏览器中都是受支持的,不会给您带来任何问题。 请注意,月份是从0到11。