-2

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

3 Answers3

1

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

Maxim Bernard
  • 307
  • 1
  • 7
1

You must parse and format the string with the Date Class with the methods:

  • Date.parse()
  • Date.toISOString()

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:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

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.