omg*_*omg 31 javascript datetime
使用新日期时,我得到如下内容:
2009年5月29日星期五22:39:02 GMT + 0800(中国标准时间)
但我想要的是xxxx-xx-xx xx:xx:xx格式化的时间字符串
Jon*_*and 52
虽然在某些情况下它不会填充两个字符,但它可以达到我想要的效果
function getFormattedDate() {
var date = new Date();
var str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
return str;
}
Run Code Online (Sandbox Code Playgroud)
Tos*_*kan 29
乔纳森的答案缺乏领先的零.有一个简单的解决方案:
function getFormattedDate(){
var d = new Date();
d = d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2) + "-" + ('0' + d.getDate()).slice(-2) + " " + ('0' + d.getHours()).slice(-2) + ":" + ('0' + d.getMinutes()).slice(-2) + ":" + ('0' + d.getSeconds()).slice(-2);
return d;
}
Run Code Online (Sandbox Code Playgroud)
基本上加0,然后只取最后2个字符.因此031将采取31. 01将采取01 ...
您可以使用toJSON()方法获取DateTime样式格式
var today = new Date().toJSON();
// produces something like: 2012-10-29T21:54:07.609Z
Run Code Online (Sandbox Code Playgroud)
从那里你可以清理它......
抓住日期和时间:
var today = new Date().toJSON().substring(0,19).replace('T',' ');
Run Code Online (Sandbox Code Playgroud)
抓住正好的日期:
var today = new Date().toJSON().substring(0,10).replace('T',' ');
Run Code Online (Sandbox Code Playgroud)
抓住时间:
var today = new Date().toJSON().substring(10,19).replace('T',' ');
Run Code Online (Sandbox Code Playgroud)
编辑:正如其他人所指出的,这只适用于UTC.看看上面的更好的答案.