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

javascript - Getting unexpected time offset from Moment.js toISOString - Stack Overflow

programmeradmin6浏览0评论

I'm trying to get the standardized ISO 8601 date format string from Moment.js, but I'm not getting the result I expect.

Moment's toISOString() method is giving me an output with a 17-hour offset, instead of midnight:

var mom = moment("23-11-2016 00:00", "DD-MM-YYYY HH:mm");
alert(mom.toISOString());
// result: 2016-11-22T17:00:00.000Z

Why the result is not 2016-11-23T00:00:00.000Z? How I can get that format?

I'm trying to get the standardized ISO 8601 date format string from Moment.js, but I'm not getting the result I expect.

Moment's toISOString() method is giving me an output with a 17-hour offset, instead of midnight:

var mom = moment("23-11-2016 00:00", "DD-MM-YYYY HH:mm");
alert(mom.toISOString());
// result: 2016-11-22T17:00:00.000Z

Why the result is not 2016-11-23T00:00:00.000Z? How I can get that format?

Share Improve this question edited Mar 6, 2023 at 19:53 zcoop98 3,0872 gold badges23 silver badges37 bronze badges asked Nov 25, 2016 at 11:07 Dark CyberDark Cyber 2,2319 gold badges46 silver badges69 bronze badges 1
  • 1 Because by default moment parses and displays in local time, while .toISOString() always returns a timestamp in UTC. You probably have -7 hours offset from UTC. Use format() if you want to display date in local time. If your input string represents a UTC time, then use moment.utc(String, String); – VincenzoC Commented Nov 25, 2016 at 11:32
Add a ment  | 

1 Answer 1

Reset to default 16

As the doc says:

By default, moment parses and displays in local time.

while .toISOString() always returns a timestamp in UTC:

Note that .toISOString() always returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString(), as outlined in the ES2015 specification.

You probably have -7 hours offset from UTC.

Use format() if you want to display date in local time.

If your input string represents a UTC time, then use moment.utc(String, String);

发布评论

评论列表(0)

  1. 暂无评论