How do I output an ISO 8601 formatted string in JavaScript?

后端 未结 14 1519
小鲜肉
小鲜肉 2020-11-22 08:41

I have a Date object. How do I render the title portion of the following snippet?



        
14条回答
  •  滥情空心
    2020-11-22 09:08

    There is already a function called toISOString():

    var date = new Date();
    date.toISOString(); //"2011-12-19T15:28:46.493Z"
    

    If, somehow, you're on a browser that doesn't support it, I've got you covered:

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

提交回复
热议问题