0

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?

user140888
  • 609
  • 1
  • 11
  • 31
  • Using plain `JavaScript` it wouldn't be so easy. I would suggest you use a library, like `moment.js` and this would be two lines of code. http://momentjs.com/ – Christos Feb 12 '15 at 13:32
  • 1
    'Sat Feb 14 2015 00:00:00 GMT+0100 (ora solare Europa occidentale)' is a string, isn't it? – Paul Feb 12 '15 at 13:40
  • Have you forgotten comma? Sat, Feb 14 2015 00:00:00 GMT+0100 – Tymek Feb 12 '15 at 13:45

4 Answers4

1

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';
  };

}() );
}
Community
  • 1
  • 1
DWB
  • 1,544
  • 2
  • 16
  • 33
1

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.

Mathias Vonende
  • 1,400
  • 1
  • 18
  • 28
0

Take a look:

All you will need about date in JS

0

Using Date.parse() and Date.toISOString()

var input = "Sat, Feb 14 2015 00:00:00 GMT+0100"
input = Date.parse(input);
input = new Date(input);
input = input.toISOString(); // "2015-02-13T23:00:00.000Z"
Community
  • 1
  • 1
Tymek
  • 3,000
  • 1
  • 25
  • 46