Javascript date format like ISO but local

前端 未结 7 1467
广开言路
广开言路 2020-12-11 00:06

how do I format a javascript date like ISO format, but in local time?

with myDate.toISOString() I am getting the time as: \"2012-09-13T19:12:23.826Z\"

相关标签:
7条回答
  • 2020-12-11 00:31

    I don't quite understand which date did you need but I think you need

       const ISOLocaleString = d => {
           const pad = n => n < 10 ? '0'+n : n;    
           return d.getFullYear()+'-'
                + pad(d.getMonth()+1)+'-'
                + pad(d.getDate())+'T'
                + pad(d.getHours())+':'
                + pad(d.getMinutes())+':'
                + pad(d.getSeconds())+'Z'
       }
    

    or

        const ISOUTCLocaleString = d => {
            const pad = n => n<10 ? '0'+n : n;    
            return d.getUTCFullYear()+'-'
                 + pad(d.getUTCMonth()+1)+'-'
                 + pad(d.getUTCDate())+'T'
                 + pad(d.getUTCHours())+':'
                 + pad(d.getUTCMinutes())+':'
                 + pad(d.getUTCSeconds())+'Z'
        }
    
    0 讨论(0)
  • 2020-12-11 00:36

    I went with what Denis Howe said, below as a ready made function for convenience.

    Also one fix: in the original answer t-z does not work because t is a Date, not milliseconds.

    function dateToISOLikeButLocal(date) {
        const offsetMs = date.getTimezoneOffset() * 60 * 1000;
        const msLocal =  date.getTime() - offsetMs;
        const dateLocal = new Date(msLocal);
        const iso = dateLocal.toISOString();
        const isoLocal = iso.slice(0, 19);
        return isoLocal;
    }
    

    With this I get the kind of string that needed as a URL parameter:

    "2018-11-16T12:23:50"
    
    0 讨论(0)
  • 2020-12-11 00:41

    There's no direct way to do this. However, you can use toLocaleString to create a string that you can easily parse to make it an ISO string.

    This works on node:

        getLocalIsoTime(time, timezone) {
            const local = time.toLocaleString("en-US", {timeZone: timezone, hour12: false, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit"});
            return `${local.substr(6, 4)}-${local.substr(0, 2)}-${local.substr(3, 2)}T${local.substr(12, 8)}`;
        }
    

    A simpler version works on node 15+ and on most modern browsers:

        getLocalIsoTime(time, timezone) {
            return time.toLocaleString("en-CA", {timeZone: timezone, hour12: false}).replace(/, /, "T");
        }
    
    0 讨论(0)
  • 2020-12-11 00:42

    AFAIK you can't format dates in javascript (without using external libraries). The best you could do is "format it yourself". I mean:

    var date = new Date();
    var year = date.getFullYear();
    var month = date......
    
    
    var ISOdate = year + "-" + month + "-" + .... ;
    

    But there are some good libraries that will let you format dates! (read "format" as in library.getDate("YYYY-MM-DD.........");)

    EDIT:

    Moment.js seems the thing you're looking for: http://momentjs.com/

    0 讨论(0)
  • 2020-12-11 00:48

    ISO 8601 is simply a way of formatting dates and can as such can be applied to any time zone.

    Have you tried the timeZone option to the Date object's toLocaleString method?

    This question has answers with examples.

    0 讨论(0)
  • 2020-12-11 00:55

    Another method is to define a prototype on the Date object:

    Date.prototype.toLocaleISOString = function() {
      const zOffsetMs = this.getTimezoneOffset() * 60 * 1000;
      const localTimeMs = this - zOffsetMs;
      const date = new Date(localTimeMs);
      const utcOffsetHr = this.getTimezoneOffset() / 60;
      const utcOffsetSign = utcOffsetHr <= 0 ? '+' : '-';
      const utcOffsetString = utcOffsetSign + (utcOffsetHr.toString.length == 1 ? `0${utcOffsetHr}` : `${utcOffsetHr}`) + ':00';
      return date.toISOString().replace('Z', utcOffsetString);
    };
    

    And using it is as simple as:

    const date = new Date();
    console.log(date.toLocaleISOString());
    // Output: 2020-08-04T14:52:38.613-07:00
    
    0 讨论(0)
提交回复
热议问题