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

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

    Just my two sends here

    I was facing this issue with datetimes so what I did is this:

    const moment = require('moment-timezone')
    
    const date = moment.tz('America/Bogota').format()
    

    Then save date to db to be able to compare it from some query.


    To install moment-timezone

    npm i moment-timezone
    
    0 讨论(0)
  • 2020-11-22 09:39

    Here are the functions I used for this end:

    function localToGMTStingTime(localTime = null) {
        var date = localTime ? new Date(localTime) : new Date();
        return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
    };
    
    function GMTToLocalStingTime(GMTTime = null) {
        var date = GMTTime ? new Date(GMTTime) : new Date();;
        return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
    };
    
    0 讨论(0)
  • 2020-11-22 09:40

    No moment.js needed: Here's a full round trip answer, from an input type of "datetime-local" which outputs an ISOLocal string to UTCseconds at GMT and back:

    <input type="datetime-local" value="2020-02-16T19:30">
    
    isoLocal="2020-02-16T19:30"
    utcSeconds=new Date(isoLocal).getTime()/1000
    
    //here you have 1581899400 for utcSeconds
    
    let isoLocal=new Date(utcSeconds*1000-new Date().getTimezoneOffset()*60000).toISOString().substring(0,16)
    2020-02-16T19:30
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-11-22 09:43

    This is my function for the clients timezone, it's lite weight and simple

      function getCurrentDateTimeMySql() {        
          var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
          var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
          var mySqlDT = localISOTime;
          return mySqlDT;
      }
    
    0 讨论(0)
  • 2020-11-22 09:48

    You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.

    Date.prototype.getISOTimezoneOffset = function () {
        const offset = this.getTimezoneOffset();
        return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
    }
    
    Date.prototype.toISOLocaleString = function () {
        return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
            this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
            this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
            this.getMilliseconds().leftPad(3);
    }
    
    Number.prototype.leftPad = function (size) {
        var s = String(this);
        while (s.length < (size || 2)) {
            s = "0" + s;
        }
        return s;
    }
    

    Example usage:

    var date = new Date();
    console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
    // Prints "2020-08-05T16:15:46.525+10:00"
    

    I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.

    (The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)

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