1

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.

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for this. I love this datejs library, it's exactly what i needed :) Thank you again.
Glad to help. Welcome to SO. You should accept the answer by clicking the check mark if it answers your question. Thanks!
1

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

1 Comment

but changing current date on server... you know, it's bad idea )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.