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

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

    The problem with toISOString is that it gives datetime only as "Z".

    ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).

    I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.

    
    
        var timezone_offset_min = new Date().getTimezoneOffset(),
            offset_hrs = parseInt(Math.abs(timezone_offset_min/60)),
            offset_min = Math.abs(timezone_offset_min%60),
            timezone_standard;
    
        if(offset_hrs < 10)
            offset_hrs = '0' + offset_hrs;
    
        if(offset_min > 10)
            offset_min = '0' + offset_min;
    
        // getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
        // So add an opposite sign to the offset
        // If offset is 0, it means timezone is UTC
        if(timezone_offset_min < 0)
            timezone_standard = '+' + offset_hrs + ':' + offset_min;
        else if(timezone_offset_min > 0)
            timezone_standard = '-' + offset_hrs + ':' + offset_min;
        else if(timezone_offset_min == 0)
            timezone_standard = 'Z';
    
        // Timezone difference in hours and minutes
        // String such as +5:30 or -6:00 or Z
        console.log(timezone_standard); 
    
    
    

    Once you have the timezone offset in hours and minutes, you can append to a datetime string.

    I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes

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

    Shortest, but not supported by Internet Explorer 8 and earlier:

    new Date().toJSON()
    
    0 讨论(0)
  • 2020-11-22 09:15

    To extend Sean's great and concise answer with some sugar and modern syntax:

    // date.js
    
    const getMonthName = (num) => {
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Oct', 'Nov', 'Dec'];
      return months[num];
    };
    
    const formatDate = (d) => {
      const date = new Date(d);
      const year = date.getFullYear();
      const month = getMonthName(date.getMonth());
      const day = ('0' + date.getDate()).slice(-2);
      const hour = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
    
      return `${year} ${month} ${day}, ${hour}:${minutes}`;
    };
    
    module.exports = formatDate;
    

    Then eg.

    import formatDate = require('./date');
    
    const myDate = "2018-07-24T13:44:46.493Z"; // Actual value from wherever, eg. MongoDB date
    console.log(formatDate(myDate)); // 2018 Jul 24, 13:44
    
    0 讨论(0)
  • 2020-11-22 09:16

    I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:

    function toLocalIsoString(date, includeSeconds) {
        function pad(n) { return n < 10 ? '0' + n : n }
        var localIsoString = date.getFullYear() + '-'
            + pad(date.getMonth() + 1) + '-'
            + pad(date.getDate()) + 'T'
            + pad(date.getHours()) + ':'
            + pad(date.getMinutes()) + ':'
            + pad(date.getSeconds());
        if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
        return localIsoString;
    };
    

    The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:

    function getOffsetFromUTC() {
        var offset = new Date().getTimezoneOffset();
        return ((offset < 0 ? '+' : '-')
            + pad(Math.abs(offset / 60), 2)
            + ':'
            + pad(Math.abs(offset % 60), 2))
    };
    

    toLocalIsoString uses pad. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:

    // Pad a number to length using padChar
    function pad(number, length, padChar) {
        if (typeof length === 'undefined') length = 2;
        if (typeof padChar === 'undefined') padChar = '0';
        var str = "" + number;
        while (str.length < length) {
            str = padChar + str;
        }
        return str;
    }
    
    0 讨论(0)
  • 2020-11-22 09:18

    I would just use this small extension to Date - http://blog.stevenlevithan.com/archives/date-time-format

    var date = new Date(msSinceEpoch);
    date.format("isoDateTime"); // 2007-06-09T17:46:21
    
    0 讨论(0)
  • 2020-11-22 09:21

    If you don't need to support IE7, the following is a great, concise hack:

    JSON.parse(JSON.stringify(new Date()))
    
    0 讨论(0)
提交回复
热议问题