How to ISO 8601 format a Date with Timezone Offset in JavaScript?

前端 未结 11 1321
时光说笑
时光说笑 2020-11-22 09:32

Goal: Find the local time and UTC time offset then construct the URL in following format.

Example URL: /Actions/Sleep?dura

相关标签:
11条回答
  • 2020-11-22 09:53

    My answer is a slight variation for those who just want today's date in the local timezone in the YYYY-MM-DD format.

    Let me be clear:

    My Goal: get today's date in the user's timezone but formatted as ISO8601 (YYYY-MM-DD)

    Here is the code:

    new Date().toLocaleDateString("sv") // "2020-02-23" // 
    

    This works because the Sweden locale uses the ISO 8601 format.

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

    The below should work properly, and for all browsers (thanks to @MattJohnson for the tip)

    Date.prototype.toIsoString = function() {
        var tzo = -this.getTimezoneOffset(),
            dif = tzo >= 0 ? '+' : '-',
            pad = function(num) {
                var norm = Math.floor(Math.abs(num));
                return (norm < 10 ? '0' : '') + norm;
            };
        return this.getFullYear() +
            '-' + pad(this.getMonth() + 1) +
            '-' + pad(this.getDate()) +
            'T' + pad(this.getHours()) +
            ':' + pad(this.getMinutes()) +
            ':' + pad(this.getSeconds()) +
            dif + pad(tzo / 60) +
            ':' + pad(tzo % 60);
    }
    
    var dt = new Date();
    console.log(dt.toIsoString());

    0 讨论(0)
  • 2020-11-22 10:01

    getTimezoneOffset() returns the opposite sign of the format required by the spec that you referenced.

    This format is also known as ISO8601, or more precisely as RFC3339.

    In this format, UTC is represented with a Z while all other formats are represented by an offset from UTC. The meaning is the same as JavaScript's, but the order of subtraction is inverted, so the result carries the opposite sign.

    Also, there is no method on the native Date object called format, so your function in #1 will fail unless you are using a library to achieve this. Refer to this documentation.

    If you are seeking a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do this:

    var m = moment();    // get "now" as a moment
    var s = m.format();  // the ISO format is the default so no parameters are needed
    
    // sample output:   2013-07-01T17:55:13-07:00
    

    This is a well-tested, cross-browser solution, and has many other useful features.

    0 讨论(0)
  • 2020-11-22 10:02
    function setDate(){
        var now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        var timeToSet = now.toISOString().slice(0,16);
    
        /*
            If you have an element called "eventDate" like the following:
    
            <input type="datetime-local" name="eventdate" id="eventdate" />
    
            and you would like to  set the current and minimum time then use the following:
        */
    
        var elem = document.getElementById("eventDate");
        elem.value = timeToSet;
        elem.min = timeToSet;
    }
    
    0 讨论(0)
  • 2020-11-22 10:03

    I think it is worth considering that you can get the requested info with just a single API call to the standard library...

    new Date().toLocaleString( 'sv', { timeZoneName: 'short' } );
    
    // produces "2019-10-30 15:33:47 GMT−4"
    

    You would have to do text swapping if you want to add the 'T' delimiter, remove the 'GMT-', or append the ':00' to the end.

    But then you can easily play with the other options if you want to eg. use 12h time or omit the seconds etc.

    Note that I'm using Sweden as locale because it is one of the countries that uses ISO 8601 format. I think most of the ISO countries use this 'GMT-4' format for the timezone offset other then Canada which uses the time zone abbreviation eg. "EDT" for eastern-daylight-time.

    You can get the same thing from the newer standard i18n function "Intl.DateTimeFormat()" but you have to tell it to include the time via the options or it will just give date.

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