如何在 ISO 8601 中输出 javascript 中没有毫秒和 Z 的日期

How to output date in javascript in ISO 8601 without milliseconds and with Z

这是在 JavaScript 中将日期序列化为 ISO 8601 字符串的标准方法:

var now = new Date();
console.log( now.toISOString() );
// outputs '2015-12-02T21:45:22.279Z'

我只需要相同的输出,但不需要毫秒。我怎样才能输出 2015-12-02T21:45:22Z

简单的方法:

console.log( new Date().toISOString().split('.')[0]+"Z" );

使用切片去除不需要的部分

var now = new Date();
alert( now.toISOString().slice(0,-5)+"Z");

这是解决方案:

var now = new Date(); 
var str = now.toISOString();
var res = str.replace(/\.[0-9]{3}/, '');
alert(res);

找到 . (点)并删除 3 个字符。

http://jsfiddle.net/boglab/wzudeyxL/7/

或者可能用这个覆盖它? (这是来自 here 的修改后的 polyfill)

function pad(number) {
  if (number < 10) {
    return '0' + number;
  }
  return number;
}

Date.prototype.toISOString = function() {
  return this.getUTCFullYear() +
    '-' + pad(this.getUTCMonth() + 1) +
    '-' + pad(this.getUTCDate()) +
    'T' + pad(this.getUTCHours()) +
    ':' + pad(this.getUTCMinutes()) +
    ':' + pad(this.getUTCSeconds()) +
    'Z';
};

您可以使用 split() and shift() to remove the milliseconds from an ISO 8601 字符串的组合:

let date = new Date().toISOString().split('.').shift() + 'Z';

console.log(date);

类似于@STORM的回答:

const date = new Date();

console.log(date.toISOString());
console.log(date.toISOString().replace(/[.]\d+/, ''));