Convert date to another timezone in JavaScript

后端 未结 24 3097
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 04:45

I am looking for a function to convert date in one timezone to another.

It need two parameters,

  • date (in format \"2012/04/10 10:10:30 +0000\")
相关标签:
24条回答
  • 2020-11-21 05:23

    People familiar with the java 8 java.time package, or joda-time will probably love the new kid on the block: the js-joda library.

    Install

    npm install js-joda js-joda-timezone --save
    

    Example

    <script src="node_modules/js-joda/dist/js-joda.js"></script>
    <script src="node_modules/js-joda-timezone/dist/js-joda-timezone.js"></script>
    <script>
    var dateStr = '2012/04/10 10:10:30 +0000';
    JSJoda.use(JSJodaTimezone);
    var j = JSJoda;
    // https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html#static-method-of-pattern
    var zonedDateTime = j.ZonedDateTime.parse(dateStr, j.DateTimeFormatter.ofPattern('yyyy/MM/dd HH:mm:ss xx'));
    var adjustedZonedDateTime = zonedDateTime.withZoneSameInstant(j.ZoneId.of('America/New_York'));
    console.log(zonedDateTime.toString(), '=>', adjustedZonedDateTime.toString());
    // 2012-04-10T10:10:30Z => 2012-04-10T06:10:30-04:00[America/New_York]
    </script>
    

    In true java nature, it's pretty verbose lol. But, being a ported java library, especially considering they ported 1800'ish test cases, it also probably works superbly accurately.

    Chrono manipulation is hard. That's why many other libraries are buggy in edge cases. Moment.js seems to get timezones right, but the other js libs I've seen, including timezone-js, don't seem trustworthy.

    0 讨论(0)
  • 2020-11-21 05:25

    I should note that I am restricted with respect to which external libraries that I can use. moment.js and timezone-js were NOT an option for me.

    The js date object that I have is in UTC. I needed to get the date AND time from this date in a specific timezone('America/Chicago' in my case).

     var currentUtcTime = new Date(); // This is in UTC
    
     // Converts the UTC time to a locale specific format, including adjusting for timezone.
     var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
    
     console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
     console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
     console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
     console.log('currentDateTimeCentralTimeZone: ' +        currentDateTimeCentralTimeZone.toLocaleDateString());
     console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
     console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());
    

    UTC is currently 6 hours ahead of 'America/Chicago'. Output is:

    currentUtcTime: 11/25/2016
    currentUtcTime Hour: 16
    currentUtcTime Minute: 15
    
    currentDateTimeCentralTimeZone: 11/25/2016
    currentDateTimeCentralTimeZone Hour: 10
    currentDateTimeCentralTimeZone Minute: 15
    
    0 讨论(0)
  • 2020-11-21 05:26

    Provide the desired time zone, for example "Asia/Tehran" to change the current time to that timezone. I used "Asia/Seoul".

    You can use the following codes. change the style if you need to do so.

    please keep in mind that if you want to have h:m:s format instead of HH:MM:SS, you'll have to remove "function kcwcheckT(i)".

    function kcwcheckT(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
    function kcwt() {
    var d = new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"});
    d = new Date(d);
      var h = d.getHours();
      var m = d.getMinutes();
      var s = d.getSeconds();
      h = kcwcheckT(h);
      m = kcwcheckT(m);
      s = kcwcheckT(s);
      document.getElementById("kcwcurtime").innerHTML = h + ":" + m + ":" + s;
      var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    document.getElementById("kcwcurday").innerHTML = days[d.getDay()]
    }
    kcwt();
    window.setInterval(kcwt, 1000);
    @import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');
    
    .kcwsource {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
    .kcwsource p {font-family: 'Nunito', sans-serif;}
    
    
    .CurTbx {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
    .kcwcstyle {font-family: 'Nunito', sans-serif; font-size: 22px;display: inline-block;}
    .kcwcurstinf {font-family: 'Nunito', sans-serif; font-size: 18px;display: inline-block;margin: 0;}
    .kcwcurday {margin: 0;}
    .kcwcurst {margin: 0 10px 0 5px;}
    
    /*Using the css below you can make your style responsive!*/
    
    @media (max-width: 600px){
      .kcwcstyle {font-size: 14px;}
      .kcwcurstinf {font-size: 12px;}
    }
    <div class="kcwsource"><p>This Pen was originally developed for <a href="http://kocowafa.com" target="_blank">KOCOWAFA.com</a></p></div>
    <div class="CurTbx"><p class="kcwcurst kcwcstyle" id="kcwcurday"></p><p class="kcwcurst kcwcstyle" id="kcwcurtime"></p><p class="kcwcurstinf">(Seoul, Korea)</p></div>

    0 讨论(0)
  • 2020-11-21 05:28

    Got it !

    Wanted to force the date shown = server date, no mattter the local settings (UTC).

    My server is GMT-6 --> new Date().getTimezoneOffset() = 360.

    myTZO = 360;
    myNewDate=new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
    alert(myNewDate);
    
    0 讨论(0)
  • 2020-11-21 05:30

    Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.

    new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' })
    
    0 讨论(0)
  • 2020-11-21 05:31

    there is an npm module called 'timezones.json' you can use for this; it basically consists of a json file with objects containing information on daylight savings and offset,....

    for asia/jakarta it would be able to return this object:

    {
      "value": "SE Asia Standard Time",
      "abbr": "SAST",
      "offset": 7,
      "isdst": false,
      "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta",
      "utc": [
        "Antarctica/Davis",
        "Asia/Bangkok",
        "Asia/Hovd",
        "Asia/Jakarta",
        "Asia/Phnom_Penh",
        "Asia/Pontianak",
        "Asia/Saigon",
        "Asia/Vientiane",
        "Etc/GMT-7",
        "Indian/Christmas"
      ]
    }
    

    you can find it here:

    https://github.com/dmfilipenko/timezones.json

    https://www.npmjs.com/package/timezones.json

    hope it's useful

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