Formatting a date to the senders local time

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:26:28.744Z and I need to turn it into a timestamp of the senders local time. For the sake of this example lets say the offset is 6 hours.

I know that this is probably wrong and that the z portion explains what the offset really is.

I need to turn 2017-06-21T20:26:28.744Z into 2017-06-21T14:26:28 using moment.

Doing this seems to give me the UTC portion of the string and chops off the offset. I need to use the offset to adjust the hours/ minutes back

moment
  .utc('2017-06-21T20:26:28.744Z')
  .local()
  .format('YYYY-MM-DDTHH:mm:ss')
  // 2017-06-21T20:26:28" 
  // I need 2017-06-21T14:26:28

Answers:

Answer

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>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.