简体   繁体   中英

“Invalid date” parsing date with moment.js

I'm trying to calculate the relative date from a given one like the following

Mon Nov 21 11:48:33 CET 2016

I think the given date follows this pattern:

EEE MMM d HH:mm:ss zzz yyyy

So, I'm trying to get the relative date with this line:

moment("Mon Nov 21 11:48:33 CET 2016", "EEE MMM d HH:mm:ss zzz yyyy").fromNow();   

But I'm receiving an "Invalid date"...

I've changed the "EEE" for "ddd" following some advices but then I'm getting a bad relative date.

moment("Mon Nov 21 12:30:40 CET 2016", "ddd MMM d HH:mm:ss zzz yyyy").fromNow() > 20 days ago

Any idea about what I'm doing wrong?

Thank you so much!

Assuming you're using moment-timezone in addition to Moment, there are a few problems:

  1. zzz is invalid undocumented; it's just z . (It seems to be allowed, though.)
  2. EEE is invalid. E is for day numbers. You wanted ddd (day name). See the documentation .
  3. You've also used d (day name) where you wanted D or DD (day of month number). Again, see the docs linked above.

This works with moment+moment-timezone:

moment("Mon Nov 21 11:48:33 CET 2016", "ddd MMM D HH:mm:ss z yyyy").fromNow();
// -------------------------------------^^^-----^----------^

Example:

 console.log(moment("Mon Nov 21 11:48:33 CET 2016", "ddd MMM D HH:mm:ss z yyyy").fromNow()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.9/moment-timezone-with-data-2010-2020.min.js"></script> 

However , I don't think Moment supports parsing that z , because I can't find anything in the Moment Timezone docs saying it enhances parsing, and when I run the above, it acts as though the date/time is in my timezone (GMT), not CET; and in fact I can swap in any timezone indicator I want (EST, PST, etc.) and it still treats the string as my local time.

For Day of the week use ddd

Check http://momentjs.com/docs/ for more information on formats.

 console.log(moment("Mon Nov 21 11:48:33 CET 2016", "ddd MMM d HH:mm:ss zzz yyyy").fromNow()); 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script> 

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