when using new Date,I get something like follows:
Fri May 29 2009 22:39:02 GMT+0800 (China Standard Time)
but what I want is xxxx-xx-xx xx:xx:xx formatted time string
when using new Date,I get something like follows:
Fri May 29 2009 22:39:02 GMT+0800 (China Standard Time)
but what I want is xxxx-xx-xx xx:xx:xx formatted time string
it may be overkill for what you want, but have you looked into datejs ?
Although it doesn't pad to two characters in some of the cases, it does what I expect you want
function getFormattedDate() {
var date = new Date();
var str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
return str;
}
What you are looking for is toISOString that will be a part of ECMAScript Fifth Edition. In the meantime you could simply use the toJSON method found in json2.js from json.org.
The portion of interest to you would be:
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.toUTCArray= function(){
var D= this;
return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
D.getUTCMinutes(), D.getUTCSeconds()];
}
Date.prototype.toISO= function(t){
var tem, A= this.toUTCArray(), i= 0;
A[1]+= 1;
while(i++<7){
tem= A[i];
if(tem<10) A[i]= '0'+tem;
}
return A.splice(0, 3).join('-')+'T'+A.join(':');
// you can use a space instead of 'T' here
}
Date.fromISO= function(s){
var i= 0, A= s.split(/\D+/);
while(i++<7){
if(!A[i]) A[i]= 0;
else A[i]= parseInt(A[i], 10);
}
--s[1];
return new Date(Date.UTC(A[0], A[1], A[2], A[3], A[4], A[5]));
}
var D= new Date();
var s1= D.toISO();
var s2= Date.fromISO(s1);
alert('ISO= '+s1+'\nlocal Date returned:\n'+s2);