简体   繁体   中英

Parsing an arbitrary date/time with moment.js

I am extracting a date from an email (in many possible formats) and then passing it to an app that expects ISO format. I'm told I can use moment.js to parse a date in various formats.

Found: 1/22/2016
Milliseconds: 1453449600000
ISO: Fri Jan 22 2016 00:00:00 GMT-0800 (PST)

Found: Jan 22 2016
Milliseconds: 1453449600000
ISO: Fri Jan 22 2016 00:00:00 GMT-0800 (PST)

Found: 2016/1/22 03:00
Milliseconds: 1453460400000
ISO: Fri Jan 22 2016 03:00:00 GMT-0800 (PST)

How do I use moment to parse all of these formats and more?

var foundDue = taskNote.match(/(Deadline|Due):.*(\n|$)/ig);
// if we've found a deadline date...
if (foundDue) {
    // Remove deadline/due tag
    foundDue = foundDue[0].replace(/(Deadline|Due):? */i, "");
    // Remove trailing and leading spaces
    foundDue = foundDue.replace(/(^\s*|\s$)*/, "");
    console.log("Found: "+ foundDue);
    // Use a magic method to parse date
    milliseconds = moment.??????(foundDue);
    console.log("Milliseconds: "+ milliseconds);
    console.log("Parsed2: "+ new Date(foundDue));
    var taskDue = new Date(milliseconds);
    console.log("ISO: "+ taskDue);
}

Note, this question is adapted from an earlier question .

You can use moment parsing with multiple formats to convert your input strings into moment objects, then you can use moment valueOf() to get milliseconds.

Here an example snippet for the inputs given in your question:

 var inputs = ['1/22/2016', 'Jan 22 2016', '2016/1/22 03:00']; for(var i=0; i<inputs.length; i++){ var m = moment(inputs[i], ['M/D/YYYY', 'MMM D YYYY', 'YYYY/M/D HH:mm']); console.log(m.format(), m.valueOf()); } 
 <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script> 

Note that, as the docs says, when using multiple formats:

Moment uses some simple heuristics to determine which format to use. In order:

  • Prefer formats resulting in valid dates over invalid ones.
  • Prefer formats that parse more of the string than less and use more of the format than less, ie prefer stricter parsing.
  • Prefer formats earlier in the array than later.

In the code sample above, ambiguous inputs like 01/02/2016 will always be parsed as January 2nd 2016 .

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