How do I convert a string to date using JavaScript?
Example:
Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time)
I want to convert it to:
YYYY-mm-dd H:i:s
How do I convert a string to date using JavaScript?
Example:
Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time)
I want to convert it to:
YYYY-mm-dd H:i:s
The Date
constructor accepts strings representing dates, example :
var date = new Date("Wed May 21 2014 02:40:00");
alert(date.getDate()); // 21
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You must parse and format the string with the Date Class with the methods:
For example:
var text = "Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time)";
var date = new Date(Date.parse(text));
var formatedText = date.toISOString();
console.log(formatedText );
If you need a custom format, try to use a custom formater, for example:
function pad(number) {
if ( number < 10 ) {
return '0' + number;
}
return number;
}
function toCustom(date) {
return date.getUTCFullYear() +
'-' + pad( date.getUTCMonth() + 1 ) +
'-' + pad( date.getUTCDate() ) +
' ' + pad( date.getUTCHours() ) +
':' + pad( date.getUTCMinutes() ) +
':' + pad( date.getUTCSeconds() );
};
These may be very useful:
You can even translate it with my plugin. It's as simple as:
$(selector).setDate({format: "+Y-+m-+d +H:+ii:+ss"; date: 'Wed May 21 2014 02:40:00'});
https://github.com/Masquerade-Circus/setDate.js
You can pass a date object too, no need to get the string of the date.