Updating time offset with moment().utcOffset()

时光怂恿深爱的人放手 提交于 2019-12-30 03:50:11

问题


I'm facing some issue trying to use moment.js for dealing with time offsets.

I collect in an hidden input the local user time offset:

<script type="text/javascript">
  $(document).ready(function () { 
    $('input#timeoffset').val(moment().utcOffset()); 
  });
</script>

The offset gets correctly stored (in my case its value is -240). Later on the server side (which runs in utc time) I try to update some db stored utcDate doing something like:

var userDate = moment(utcDate).utcOffset(offset)

My issue is the following: if I run my code as above described I get no effects:

  • utcDate: 20151001 012421 +0000
  • userDate: 20151001 012421 +0000

If I flip the offset sign I get:

  • utcDate: 20151001 012421 +0000
  • userDate: 20151001 052421 +0400

I'm clearly doing something wrong (even if my expectation was that the first version was correct), do you have any hint?

On client-side I'm using moment.js v2.10.6 while on the server-side moment-timezone.js v0.4.0 and moment.js v2.10.6


回答1:


The main issue is that you are passing the offset as a string instead of a number.

moment.utc("2015-10-01 01:24:21").utcOffset("-240").format('YYYYMMDD HHmmss ZZ')
// "20151001 012421 +0000"

moment.utc("2015-10-01 01:24:21").utcOffset(-240).format('YYYYMMDD HHmmss ZZ')
// "20150930 212421 -0400"

When you have an offset in terms of minutes, then you must use the numeric form. You can always convert it:

moment.utc("2015-10-01 01:24:21").utcOffset(+"-240").format('YYYYMMDD HHmmss ZZ')
// "20150930 212421 -0400"

Moment does allow for offsets to be passed as strings, but it expects them to be in one of the ISO8601 formats: either [+/-]HH:mm or [+/-]HHmm.

moment.utc("2015-10-01 01:24:21").utcOffset("-04:00").format('YYYYMMDD HHmmss ZZ')
// "20150930 212421 -0400"

Additionally, note that I used moment.utc(...) to parse the input string. You just used moment(...) which will use the local time zone unless the time zone is explicit or if you pass a Date object instead of a string. It will also leave the moment object in "local mode", so your utcDate output would be wrong unless the time zone of the machine was actually set to UTC.

Lastly, don't forget "Time Zone != Offset". You can't assume that the offset you obtained is valid for all dates. If you need to project a date to to the user's time zone, you have to actually know the time zone, such as America/New_York. You can use these with the moment-timezone plugin.



来源:https://stackoverflow.com/questions/32878197/updating-time-offset-with-moment-utcoffset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!