How can I convert a date in this format 'Sat Feb 14 2015 00:00:00 GMT+0100 (ora solare Europa occidentale)' into a date in this format '2015-02-05T10:17:13' using javascript?
4 Answers
There is a library, called moment.js. With it, you can parse datetime-strings in many representational formats, and convert them back, in whatever datetime format you like.
Comments
The date you want to get to is basically the ISO-8601 standard.
var date = new Date('Sat Feb 14 2015 00:00:00 GMT+0100');
var iso8601 = date.toISOString();
console.log(iso8601); // 2015-02-13T23:00:00.000Z
This conversion is based on ECMAScript 5 (ECMA-262 5th edition) so won't be available in older versions of JS. Other answers are correct moment js will significantly improve your date conversions.
Courtesy of this MDN Page and this stack overflow question. If you expect to be supporting pre EC5 you can use the polyfill:
if ( !Date.prototype.toISOString ) {
( function() {
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear()
+ '-' + pad( this.getUTCMonth() + 1 )
+ '-' + pad( this.getUTCDate() )
+ 'T' + pad( this.getUTCHours() )
+ ':' + pad( this.getUTCMinutes() )
+ ':' + pad( this.getUTCSeconds() )
+ '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+ 'Z';
};
}() );
}
JavaScriptit wouldn't be so easy. I would suggest you use a library, likemoment.jsand this would be two lines of code. momentjs.com