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?

3
  • 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. momentjs.com Commented Feb 12, 2015 at 13:32
  • 1
    'Sat Feb 14 2015 00:00:00 GMT+0100 (ora solare Europa occidentale)' is a string, isn't it? Commented Feb 12, 2015 at 13:40
  • Have you forgotten comma? Sat, Feb 14 2015 00:00:00 GMT+0100 Commented Feb 12, 2015 at 13:45

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

}() );
}

Comments

0

Take a look:

All you will need about date in JS

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.