0

I have given a very unusual date format in string. I need to convert it to a JS date object and add up a few days. The last step is clear, but I don't know how to convert the string into the JS date object. Take a look at the string date: October 02, 2016

2
  • 1
    datestr.match(/(\w+) (\d+), (\d+)/) and go from there? Commented Sep 30, 2016 at 10:23
  • Take a look at momentjs, it has some nice functions to do things like this. Commented Sep 30, 2016 at 10:24

4 Answers 4

1

You should use moment.js

Syntax:

moment(dateString, format, locale)

var dateStr = "Oktober 02, 2016"
var d = moment(dateStr, "MMM DD, YYYY", 'de');
console.log(d.format("DD-MM-YYYY"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment-with-locales.min.js"></script>

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

1 Comment

This is it. Thank you. The other answers are surely good as well, but I searched for a good JS framework like this. Thanks!
0

Use Date.parse() to parse the date and get the Date object.

var dateObj = new Date('October 02, 2016')

Now, you can perform all the Date operations on dateObj

1 Comment

You are missing Language too.
0

Given that everything is static here, I thing the best case for you might be to keep a map of your month's name against there number i.e say Oktober : 8. This way you will easily get around of any locale issue in any library.

Once above map is done, you can use .substring to separate your string for blank space and commas to get date and year easily.

Once you have all this you can use new Date constructor with months date and year field.

Hope this all is easily understood, so I am skipping any code here.

Comments

0

Using new Date() can be converted from string to date. And using setDate() you can add days in the date and can convert the date back to string, Please check below snippet for more understanding.

var someDate = new Date('October 02, 2016');
console.log(someDate);
console.log(new Date(someDate.setDate(someDate.getDate() + 5)).toString()); 

Comments

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.