我使用JS函数toLocaleString
进行日期格式化。如何为所有客户设置一种通用格式,如:
2015-10-29 20:00:00
我通过-
答案 0 :(得分:2)
我认为您必须手动将其解析为该格式,实际上并不太糟糕。 Date.toLocaleString()返回的格式为:
MM/DD/YYYY, HH:MM:SS
这是我的代码段,可以帮助您:
// Parse our locale string to [date, time]
var date = new Date().toLocaleString('en-US',{hour12:false}).split(" ");
// Now we can access our time at date[1], and monthdayyear @ date[0]
var time = date[1];
var mdy = date[0];
// We then parse the mdy into parts
mdy = mdy.split('/');
var month = parseInt(mdy[0]);
var day = parseInt(mdy[1]);
var year = parseInt(mdy[2]);
// Putting it all together
var formattedDate = year + '-' + month + '-' + day + ' ' + time;
答案 1 :(得分:-1)
var el = document.getElementById('dbg');
var log = function(val){el.innerHTML+='<div><pre>'+val+'</pre></div>'};
var pad = function(val){ return ('00' + val).slice(-2)};
Date.prototype.myFormattedString = function(){
return this.getFullYear() + '-' +
pad( (this.getMonth() + 1) ) + '-' +
pad( this.getDate() ) + ' ' +
pad( this.getHours() ) + ':' +
pad( this.getMinutes() ) + ':' +
pad( this.getSeconds() )
;
}
var curDate = new Date();
log( curDate )
log( curDate.toLocaleString() )
log( curDate.myFormattedString() )
&#13;
<div id='dbg'></div>
&#13;