user140888
user140888

Reputation: 609

Convert date into different formats in javascript

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?

Upvotes: 0

Views: 1050

Answers (4)

DWB
DWB

Reputation: 1554

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

}() );
}

Upvotes: 1

Tymek
Tymek

Reputation: 3113

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"

Upvotes: 0

Shargonautes
Shargonautes

Reputation: 11

Take a look:

All you will need about date in JS

Upvotes: 0

Mathias Vonende
Mathias Vonende

Reputation: 1380

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.

Upvotes: 1

Related Questions