为什么这段代码会在明天的日期返回?
由于我们是8月31日,它必须返回2013-08-31而不是2013-09-01.
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toisostring
function myFunction() {
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML = d.toISOString();
}Run Code Online (Sandbox Code Playgroud)
<p id="demo">Click the button to display the date and time as a string, using the ISO
standard.</p>
<button onclick="myFunction()">Try it</button>Run Code Online (Sandbox Code Playgroud)
是 UTC 时间。
如果您想获取本地时区,您必须自己格式化日期(使用getYear() getMonth()等)或使用某些库(例如date.js)来为您格式化日期。
使用 date.js 非常简单:
(new Date()).format('yyyy-MM-dd')
Run Code Online (Sandbox Code Playgroud)
编辑
正如 @MattJohnson 指出的 date.js 已被放弃,但您可以使用像moment.js这样的替代品。
使用:
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
Run Code Online (Sandbox Code Playgroud)
或者
(function() {
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
Date.prototype.toISO1String = function() {
return this.getFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds()) +
'.' + (this.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
'Z';
};
})();
Run Code Online (Sandbox Code Playgroud)
请参阅:mozilla.org toISOString 文档
我刚刚修改过
| 归档时间: |
|
| 查看次数: |
7786 次 |
| 最近记录: |