简体   繁体   中英

Parsing formatted date with moment js

I'm formatting incoming date 2016-11-10T21:59:53.000+0000 with help moment js as:

  myService.getDate(id)
       .then(function (data) {
           data.occuredDate = moment.utc(new Date(data.occuredDate)).format('DD MMM YYYY h:mm a');
       };

the output result looks like: 10 Nov 2016 10:00 pm

Now I'm trying to parse this date back to string, but unfortunately my attempts are unsuccessful

  console.log(new Date(obj.occuredDate))
  console.log(new Date(obj.occuredDate).toString())
  console.log(Date.parse(obj.occuredDate))
  console.log(new Date(Date.parse(obj.occuredDate)))
  console.log(new Date(Date.parse(obj.occuredDate)).toString())

  Invalid Date
  Invalid Date
  NaN
  Invalid Date
  Invalid Date

Could anybody explain me what I'm doing wrong?

Thanks in advance.

As you are parsing a non standard format, simply specify the format. Then use moment's toDate() method to get a plain js Date object:

moment.utc(obj.occuredDate, 'DD MMM YYYY h:mm a').toDate();

SIDENODE

Using moment.utc(new Date(data.occuredDate)) doesn't really make sense. Just parse the string.

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