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

前端 未结 11 1537
时光说笑
时光说笑 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:42

    Check this:

    function dateToLocalISO(date) {
        const off    = date.getTimezoneOffset()
        const absoff = Math.abs(off)
        return (new Date(date.getTime() - off*60*1000).toISOString().substr(0,23) +
                (off > 0 ? '-' : '+') + 
                (absoff / 60).toFixed(0).padStart(2,'0') + ':' + 
                (absoff % 60).toString().padStart(2,'0'))
    }
    
    // Test it:
    d = new Date()
    
    dateToLocalISO(d)
    // ==> '2019-06-21T16:07:22.181-03:00'
    
    // Is similar to:
    
    moment = require('moment')
    moment(d).format('YYYY-MM-DDTHH:mm:ss.SSSZ') 
    // ==> '2019-06-21T16:07:22.181-03:00'
    

提交回复
热议问题