Get date time for a specific time zone using JavaScript

前端 未结 5 1629
孤城傲影
孤城傲影 2020-12-24 06:20

It seems that JavaScript\'s Date() function can only return local date and time. Is there anyway to get time for a specific time zone, e.g., GMT-9?

Combining @​Esail

相关标签:
5条回答
  • 2020-12-24 06:40

    You can do this in one line:

    let d = new Date(new Date().toLocaleString("en-US", {timeZone: "timezone id"})); // timezone ex: Asia/Jerusalem
    
    0 讨论(0)
  • 2020-12-24 06:42
    var today = new Date();  
    var offset = -(today.getTimezoneOffset()/60);  
    
    0 讨论(0)
  • 2020-12-24 06:48

    There is simple library for working on timezones easily called TimezoneJS can be found at https://github.com/mde/timezone-js.

    0 讨论(0)
  • 2020-12-24 06:55
    var offset = -8;
    new Date( new Date().getTime() + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )
    
    "Wed, 20 Jun 2012 08:55:20"
    

    <script>
      var offset = -8;
    
      document.write(
        new Date(
          new Date().getTime() + offset * 3600 * 1000
        ).toUTCString().replace( / GMT$/, "" )
      );
    </script>

    0 讨论(0)
  • 2020-12-24 06:55

    You can always get GMT time (so long as the client's clock is correct).

    To display a date in an arbitrary time-zone, construct a string from the UTC hours, minutes, and seconds after adding the offset.

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