简体   繁体   中英

Moment.js Date Returning Invalid

I have a React app that is parsing some dates using Moment.js/Timezones. I'm getting data from an API, and many dates return correct and are parsed but a few aren't. For example, this date: 2018-04-03T02:10:00Z parses correctly where as this one does not: 2018-04-03T01:40:00Z . I don't see any reason why this should be the case.

I am using moment.timezone to guess the users timezone:

this.state = {
  userZone: moment.tz.guess()
}

and then mapping through my API response and outputting the date (or state of the game if in progress).

{this.props.status === 'Scheduled' ? moment(this.props.gameDate, 'YYYY-MM-DDTHH:MM00Z').tz(this.state.userZone).format('h:MM A z') : this.props.status}

I'm pretty stumped as to why this is happening to only a few dates and have actually been spinning my wheels on this off and on for 4 months... Any thoughts? Thanks!

You have some issue in the way you are parsing your input. Since it is in ISO 8601 compliant format you can use moment(String) instead of moment(String, String) .

You code could be like the following:

{this.props.status === 'Scheduled' ? moment(this.props.gameDate).tz(this.state.userZone).format('h:mm A z') : this.props.status}

In your question you are using 'YYYY-MM-DDTHH:MM00Z' as format parameter of moment(String, String) , the problem is that format tokens are case sensitive: uppercase MM stands for month's number while lovercase mm stands for minutes. 2018-04-03T01:40:00Z gives invalid date because with your code you are tring to parse 40 as month number.

See here an example on how to use moment(String, String) to parse ISO 8601 compliant inputs and take a look at moment.utc if you want to explicitly parse you UTC input in UTC mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM