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 s
Try this.
var datetime = new Date().toJSON().slice(0,10)
+ " " + new Date(new Date()).toString().split(' ')[4];
console.log(datetime);
Converting Milliseconds to date formate using javascript
http://jsfiddle.net/kavithaReddy/cspn3pj0/1/
function () {
var values = "/Date(1409819809000)/";
var dt = new Date(parseInt(values.substring(6, values.length - 2)));
var dtString1 = (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
alert(dtString1);
})();
jonathan's answers lacks the leading zero. There is a simple solution to this:
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;
}
basically add 0 and then just take the 2 last characters. So 031 will take 31. 01 will take 01...
jsfiddle
it may be overkill for what you want, but have you looked into datejs ?
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);
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() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
return str;
}