I have a string which is allways in this format: 7 May 2012 or 17 May 2012
My goal is to parse this string and get the date in this format: yyyy-mm-dd
So, my example 7 May 2012 will become 2012-05-07 and 17 May 2012 will become 2012-05-17
I have tryed with
Date.parse("7 May 2012", "yyyy-mm-dd")
but the result is:
Sun May 20 2012 00:00:00 GMT+0200 (CEST)
Thank you very much for your help.
I don’t know where you got that
Date.parsecall, JavaScript’sDate.parsehas no second argument.To do this, you’ll need to parse the string yourself, or use MomentJS or similar to do it for you. If you want to parse it yourself, you’ll probably want a regular expression and a lookup table (for the month names). The regex would be along these lines:
…where you’d end up with
parts[0]being the day,parts[1]the month name, andparts[2]the year. Then just convert the month to lower or upper case, and use a lookup table to map month name to month number, something along these lines:Live example | source
Then you can format the resulting
Dateobject. (Again, there are libs to help there.)Or, of course, never actually make a
Dateand just format directly fromparts.