将日期格式化为发件人本地时间 [英] Formatting a date to the senders local time

查看:85
本文介绍了将日期格式化为发件人本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难获取带有偏移量的UTC日期字符串,并将时间精确地调整为用户的本地时间.我在服务器上收到一个日期,说:2017-06-21T20:26:28.744Z,我需要将其转换为发件人本地时间的时间戳.为了这个例子,可以说偏移量是6小时.

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.

我知道这可能是错误的,并且z部分说明了偏移量的真正含义..

我需要用力矩将2017-06-21T20:26:28.744Z变成2017-06-21T14:26:28.

这样做似乎给了我字符串的UTC部分并砍掉了偏移量.我需要使用偏移量来调整小时/分钟

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

推荐答案

您可以使用 utcOffset

You can use utcOffset

通过提供分钟数来设置UTC偏移量.请注意,一旦设置了偏移量,它便会固定不变,不会单独更改(即没有DST规则).如果您想要一个实际的时区-在特定位置的时间,例如America/Los_Angeles,请考虑 moment-timezone .

如果输入小于16且大于-16,则会将您的输入解释为小时.

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

这里是一个工作示例:

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>

这篇关于将日期格式化为发件人本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆