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

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

提交回复
热议问题