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

后端 未结 14 1659
小鲜肉
小鲜肉 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: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)
    

提交回复
热议问题