Formatting a date to the senders local time

后端 未结 1 344
心在旅途
心在旅途 2021-01-26 01:51

I am having a hard time taking a UTC Date string with an offset and adjusting the time to the users local time exactly. I receive a date on our server say: 2017-06-21T20:2

相关标签:
1条回答
  • 2021-01-26 02:16

    You can use utcOffset

    Setting the UTC offset by supplying minutes. Note that once you set an offset, it's fixed and won't change on its own (i.e there are no DST rules). If you want an actual time zone -- time in a particular location, like America/Los_Angeles, consider moment-timezone.

    If the input is less than 16 and greater than -16, it will interpret your input as hours instead.

    Here a working sample:

    console.log( moment
      .utc('2017-06-21T20:26:28.744Z')
      .utcOffset(-6)
      .format('YYYY-MM-DDTHH:mm:ss') );
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

    If you want to use moment-timezone, you can use tz() method:

    console.log( moment
      .utc('2017-06-21T20:26:28.744Z')
      .tz('America/Chicago')
      .format('YYYY-MM-DDTHH:mm:ss') );
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>

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