Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse date(s) out of arbitrary string

So I need to write a module/function that would analyse a string and parse all possible date values given in any arbitrary form, eg:

bla-bla-bla today        --> new Date()
january foo Mar 11th bar --> [new Date('2014/1/1'), new Date('2014/3/11')]  // more than one date
lorem 11/08 ipsum        -->  new Date('2014/11/08')
monday                   -->  new Date('2014/10/27')  

How difficult would it be? Should I even bother trying, or it's a lot more difficult than I'm imagining? Maybe someone has already done something like that?

Only dates, time doesn't really matter, also I need to do it on the client, crazy eh?

like image 811
iLemming Avatar asked Mar 12 '26 09:03

iLemming


2 Answers

One solution is to use http://momentjs.com/docs/#/plugins/parseformat/

Good luck!

like image 125
mkelley33 Avatar answered Mar 14 '26 23:03

mkelley33


I really depends on how custom you're looking to make it. Your best bet is really to exhaust the current options out there, http://momentjs.com/ or even the thing it "replaced", http://www.datejs.com/. Those libraries aren't meant to do that but you might be able to either contort them to do so or fork them and modify them for your purposes.

If you can't get something custom enough out of those I would recommend going the route of describing the date syntax you want as more of a grammer, then using a parser or parser generator to create something that can correctly parse what you want. Something in the realm of http://pegjs.majda.cz/ or http://marijnhaverbeke.nl/acorn/.

For some context I ran into a similar situation for time only and ended up using Scala's standard parser combinator library to achieve something of this sort. https://github.com/scala/scala-parser-combinators. That only worked out because I was able to express a fairly high level grammar and not get into the weeds of parsing particulars.

like image 33
T. Stone Avatar answered Mar 14 '26 21:03

T. Stone