简体   繁体   中英

Convert date into different formats in javascript

如何使用javascript将格式为“ Sat Feb 14 2015 00:00:00 GMT + 0100(ora solare Europa occidentale)”的日期转换为格式为“ 2015-02-05T10:17:13”的日期?

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

}() );
}

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM