最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Moment js UTC+00:00 giving 1 hr extra - Stack Overflow

programmeradmin2浏览0评论

I am using moment js for date formatting based on time zone. I have following example

console.log(moment("11-Apr-2017 13:00 UTC+00:00", "D-MMM-YYYY HH:mm:Z").format('x'));
<script src=".js/2.18.1/moment.min.js"></script>

I am using moment js for date formatting based on time zone. I have following example

console.log(moment("11-Apr-2017 13:00 UTC+00:00", "D-MMM-YYYY HH:mm:Z").format('x'));
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.18.1/moment.min.js"></script>

It is giving an extra hour.

Share Improve this question edited Apr 11, 2017 at 17:21 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Apr 11, 2017 at 17:11 Rishabh ShahRishabh Shah 5808 silver badges29 bronze badges 3
  • It appears to be ignoring the time zone entirely. When I run it, I get the time_t value for 11-Apr-2017 13:00 in my local time zone. – Mark Reed Commented Apr 11, 2017 at 17:27
  • 2 Because you're using moment() which parses the date into a local date/time value. For instance, when I run the code, I see it as several hours earlier, since I'm in UTC-05:00. You'll want to use moment.utc(). See stackoverflow./q/24782732/215552 for a similar issue. – Heretic Monkey Commented Apr 11, 2017 at 17:28
  • @MikeMcCaughan that's not the problem. If the specified time includes a zone, moment() will return the local time matching that specification. The problem in this case is that the format string doesn't match, so the zone is not being picked up. A simple colon addition or removal makes the code work as written without having to call .utc. – Mark Reed Commented Apr 11, 2017 at 17:34
Add a ment  | 

2 Answers 2

Reset to default 3

Your string doesn't match the format. In particular, "13:00 UTC+00:00" does not match "HH:mm:Z". So the time zone is being ignored entirely. If you are getting UTC+1:00, it's because that's where you are. I get UTC-4:00.

If you remove the : between mm and Z, or alternatively, add one between 00 and UTC, it will work:

console.log(moment("11-Apr-2017 13:00 UTC+00:00", "D-MMM-YYYY HH:mm Z").format('x'));
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Moment counts your timezone, to get the time without timezone offset (that is, without getting 1 hour added to your time) you can use either of the following

moment.utc(new Date(<date>)).format("YYYY-MM-DD HH:mm:ss")

OR

moment(new Date(<date>)).utc().format("YYYY-MM-DD HH:mm:ss")
发布评论

评论列表(0)

  1. 暂无评论