Trong hầu hết các trình duyệt mới hơn bạn có .toISOString()
phương pháp, nhưng trong IE8 trở lên bạn có thể sử dụng sau đây (lấy từ json2.js bởi Douglas Crockford):
// Override only if native toISOString is not defined
if (!Date.prototype.toISOString) {
// Here we rely on JSON serialization for dates because it matches
// the ISO standard. However, we check if JSON serializer is present
// on a page and define our own .toJSON method only if necessary
if (!Date.prototype.toJSON) {
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
}
Date.prototype.toISOString = Date.prototype.toJSON;
}
Bây giờ bạn có thể yên tâm phương pháp '.toISOString() gọi.
Nguồn
2012-07-11 20:08:36
Cố gắng không bỏ thông tin múi giờ. Xem http://stackoverflow.com/a/15302113/277267 –