JavaScript中的日期转换在Firefox中不起作用

Converting Date in JavaScript is not working in Firefox

本文关键字:Firefox 不起作用 日期 JavaScript 转换      更新时间:2023-09-26
// Date library for DateTime comparisons and checkingifa date is in-between arange of 2 dates!
// Source: http://stackoverflow.com/questions/497790
var dates = {
  // Format a Date string or object as "9/17/2015 8:15 pm"
  // var date can be;
  // - Date String = creates date object with DateTime in the string
  // - String value of "now" = creates date object with current DateTime
  // - Date Object = uses the Date object passed in
  // - null/no value = creates date object with current DateTime
  formatDate: function(date) {
      if (typeof(date) == "undefined") {
          date = new Date();
      } else if (typeof(date) == "string") {
          if (date == 'now') {
              date = new Date();
          } else {
              var date_string = date;
              date = new Date(date_string);
          }
      }
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var ampm = hours >= 12 ? 'pm' : 'am';
      hours = hours % 12;
      hours = hours ? hours : 12; // the hour '0' should be '12'
      minutes = minutes < 10 ? '0' + minutes : minutes;
      var strTime = hours + ':' + minutes + ' ' + ampm;
      return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
  },
};

Format Date in JavaScript…

console.log(dates.formatDate('2014-06-17 00:00:00'));

返回FIrefox中的NaN/NaN/NaN 12:NaN am和Chrome中的6/17/2014 12:00 am

传入没有时间的日期在Firefox中可以正常工作

console.log(dates.formatDate('2014-06-17'));

返回FIrefox中的6/16/2014 8:00 pm


我希望能够传递一个日期与时间或没有时间,并有它的工作在FIrefox和Chrome

new Date(date_string)构造函数支持与Date.parse()相同的日期格式,即RFC2822和ISO 8601。附加支持是可选的,但不是强制性的。

您的字符串不是两种支持的格式,Firefox无法识别。也可以"安全"地假设它不会被其他JavaScript引擎支持。

另一方面,如果您特别需要这种格式,您可以轻松地将其转换为ISO 8601:

alert(new Date('2014-06-17 00:00:00'.replace(' ', 'T')))