Reputation: 17
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
Upvotes: 0
Views: 52
Reputation: 5246
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());
Upvotes: 0
Reputation: 5131
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.
Upvotes: 0
Reputation: 24915
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>
Upvotes: 1
Reputation: 19113
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
Upvotes: 0