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

前端 未结 11 1296
时光说笑
时光说笑 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 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.

提交回复
热议问题