這裏是連載日期在JavaScript ISO 8601字符串的標準方式:如何輸出日期在JavaScript中的ISO 8601,而不毫秒以Z
var now = new Date();
console.log(now.toISOString());
// outputs '2015-12-02T21:45:22.279Z'
我只需要相同的輸出,但沒有毫秒。我如何輸出2015-12-02T21:45:22Z
?
這裏是連載日期在JavaScript ISO 8601字符串的標準方式:如何輸出日期在JavaScript中的ISO 8601,而不毫秒以Z
var now = new Date();
console.log(now.toISOString());
// outputs '2015-12-02T21:45:22.279Z'
我只需要相同的輸出,但沒有毫秒。我如何輸出2015-12-02T21:45:22Z
?
簡單的方法:
console.log(now.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個字符。
或可能與此覆蓋它嗎? (這是來自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';
};
在我的書中避免使用正則表達式;) – Rob