Darksody
Darksody

Reputation: 539

javascript date from string issue

I am trying to get a date object from a string from an input. I found out I can just pass the string to the Date() constructor. So if I enter "12 june 2012" into my input text, Date("12 june 2012") will give me the date object so I can convert it further into Y-m-d format, for my database.

The problem is:

If I enter just "12 june", it will automatically add the year 2001, which is the default I guess. So the result would be 2001-06-12. I want it to use the default year if no year is given. Any ideas how to do this? I don't want to parse the string, because the date can be entered in several formats, so i won't know what exactly to parse.

Thank you.

Edit: Problem solved, the datejs library did all the work :) Thank you all for the help.

Upvotes: 1

Views: 186

Answers (2)

Nayjest
Nayjest

Reputation: 1089

The problem is: If i enter just "12 june", it will automatically add the year 2001

Not year 2001 but current year will be used. If you do it on server side (Node.js, etc.), you can change current date. If it's browser -- no way

Upvotes: 1

loganfsmyth
loganfsmyth

Reputation: 161467

Not sure if there is any easy way to do that in standard JS, but you could try using a date library like this:

http://www.datejs.com/

Upvotes: 1

Related Questions