将日期格式化为发件人本地时间 [英] Formatting a date to the senders local time
问题描述
我很难获取带有偏移量的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屋!