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

后端 未结 14 1326
小鲜肉
小鲜肉 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:01
    function getdatetime() {
        d = new Date();
        return (1e3-~d.getUTCMonth()*10+d.toUTCString()+1e3+d/1)
            .replace(/1(..)..*?(\d+)\D+(\d+).(\S+).*(...)/,'$3-$1-$2T$4.$5Z')
            .replace(/-(\d)T/,'-0$1T');
    }
    

    I found the basics on Stack Overflow somewhere (I believe it was part of some other Stack Exchange code golfing), and I improved it so it works on Internet Explorer 10 or earlier as well. It's ugly, but it gets the job done.

    0 讨论(0)
  • 2020-11-22 09:02

    I was able to get below output with very less code.

    var ps = new Date('2010-04-02T14:12:07')  ;
    ps = ps.toDateString() + " " + ps.getHours() + ":"+ ps.getMinutes() + " hrs";
    

    Output:

    Fri Apr 02 2010 19:42 hrs
    
    0 讨论(0)
  • 2020-11-22 09:05

    There is a '+' missing after the 'T'

    isoDate: function(msSinceEpoch) {
      var d = new Date(msSinceEpoch);
      return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
             + d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
    }
    

    should do it.

    For the leading zeros you could use this from here:

    function PadDigits(n, totalDigits) 
    { 
        n = n.toString(); 
        var pd = ''; 
        if (totalDigits > n.length) 
        { 
            for (i=0; i < (totalDigits-n.length); i++) 
            { 
                pd += '0'; 
            } 
        } 
        return pd + n.toString(); 
    } 
    

    Using it like this:

    PadDigits(d.getUTCHours(),2)
    
    0 讨论(0)
  • 2020-11-22 09:07

    See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:

    /* Use a function for the exact format desired... */
    function ISODateString(d) {
        function pad(n) {return n<10 ? '0'+n : n}
        return d.getUTCFullYear()+'-'
             + pad(d.getUTCMonth()+1)+'-'
             + pad(d.getUTCDate())+'T'
             + pad(d.getUTCHours())+':'
             + pad(d.getUTCMinutes())+':'
             + pad(d.getUTCSeconds())+'Z'
    }
    
    var d = new Date();
    console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z
    
    0 讨论(0)
  • 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';
        };
    
      }() );
    }
    
    0 讨论(0)
  • 2020-11-22 09:12

    Almost every to-ISO method on the web drops the timezone information by applying a convert to "Z"ulu time (UTC) before outputting the string. Browser's native .toISOString() also drops timezone information.

    This discards valuable information, as the server, or recipient, can always convert a full ISO date to Zulu time or whichever timezone it requires, while still getting the timezone information of the sender.

    The best solution I've come across is to use the Moment.js javascript library and use the following code:

    To get the current ISO time with timezone information and milliseconds

    now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
    // "2013-03-08T20:11:11.234+0100"
    
    now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
    // "2013-03-08T19:11:11.234+0000"
    
    now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
    // "2013-03-08T19:11:11Z" <- better use the native .toISOString() 
    

    To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds

    var current_time = Date.now();
    moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
    

    This can be combined with Date.js to get functions like Date.today() whose result can then be passed to moment.

    A date string formatted like this is JSON compilant, and lends itself well to get stored into a database. Python and C# seem to like it.

    0 讨论(0)
提交回复
热议问题