Search code examples
javascriptdatedatejs

JavaScript compare different date formats?


I am trying to extract different date formats from a text and later compare those dates if they belong in some time span. Let' say time span is from 1.1.2013 to 1.3.2013 . This is DD/MM/YYYY time format.

Now how can I extract different time formats from text. I have here examples of time formats.

  • Tue Oct 23, 2012 7:59 am
  • February 19th, 2013, 07:32 PM
  • Today, 09:22 PM
  • Yesterday, 09:03 AM
  • 28 February 2013 09:38
  • Yesterday 16:48
  • 8 Oct 2012 5:41:00 AM
  • 02-18-2013, 03:17 PM
  • 02-01-13, 12:31 PM
  • 12.2.2013 20:43

I understand this is not a simple task to perform but any kind of suggestion can help me.

Also I am aware of this question and answers . This will benefit me later

Compare two dates with JavaScript

Also the guys on chat had this to say.

Uwe Günther
@IceD looks like you need some lib who implements that all :-) 
But ih ave noe clue which one does. Better ask the Stack

IMPORTANT

I don't want jQuery in this since I can't implement it in what I am using right now. So only JS solutions for this.


Solution

  • You will need to normalize them to a common, comparable format, most suitably Date objects.

    For some of your formats, (some browsers) will be able to Date.parse them, but for others (like "yesterday") you need to do more sophisticated parsing (up to NLP?). It would be best if you knew the format of each snippet so you can pass them to the right parsing algorithm, if not you'll need to apply some heuristics.