admin管理员组文章数量:1134244
Here is a standard way to serialise date as ISO 8601 string in JavaScript:
var now = new Date();
console.log( now.toISOString() );
// outputs '2015-12-02T21:45:22.279Z'
Here is a standard way to serialise date as ISO 8601 string in JavaScript:
var now = new Date();
console.log( now.toISOString() );
// outputs '2015-12-02T21:45:22.279Z'
I need just the same output, but without milliseconds. How can I output 2015-12-02T21:45:22Z
?
6 Answers
Reset to default 196Simple 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/
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+/, ''));
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.toISOStringShort = function() {
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'Z';
};
本文标签: How to output date in javascript in ISO 8601 without milliseconds and with ZStack Overflow
版权声明:本文标题:How to output date in javascript in ISO 8601 without milliseconds and with Z - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736811410a1953909.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
(new Date).toISOString().replace(/\.\d+/, "")
. – Константин Ван Commented May 28, 2022 at 22:27