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

以下是用 JavaScript 将日期序列化为 ISO 8601字符串的标准方法:

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

我只需要相同的输出,但没有毫秒。如何输出 2015-12-02T21:45:22Z

85313 次浏览

Simple way:

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

Use slice to remove the undesired part

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

This is the solution:

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

Finds the . (dot) and removes 3 characters.

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

or probably overwrite it with this? (this is a modified polyfill from here)

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';
};

You can use a combination of split() and shift() to remove the milliseconds from an ISO 8601 string:

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


console.log(date);

It is similar to @STORM's answer:

const date = new Date();


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