Reputation: 3733
Well I have this code:
maxdate = saved['maxdate'];
var maxdate = new Date(maxdate.split('.').reverse().join(','));
maxdate.setDate(maxdate.getDate() + 60); //add 60 days
console.log(saved['maxdate']);
console.log(maxdate);
console.log(formatDate(maxdate));
and formatDate function:
function formatDate(date) {
var monthNames = [
"01", "02", "03",
"04", "05", "06", "07",
"08", "09", "10",
"11", "12"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + '.' + monthNames[monthIndex] + '.' + year;
}
In chrome result from the console.logs is:
13.05.2019
Fri Jul 12 2019 00:00:00 GMT+0300 (Eastern European Summer Time)
12.07.2019
Everything is OK, but in IE it returns me:
13.05.2019
[date] Invalid Date[date] Invalid Date
NaN.undefined.NaN
So .. probably new Date()
doesn't work correctly in IE, any ideas ?
Upvotes: 1
Views: 51
Reputation: 15120
Parsing date strings with the Date constructor is strongly discouraged due to implementation differences across browsers (which is exactly what you experienced). If you can count on a specific format like the example in your question, it is relatively easy to parse the date string yourself and then pass the date parts to the constructor. For example (there are more elegant ways to do this, but tried to avoid any ES6 syntax below since you are using this in IE):
function parseDate(d) {
var parts = d.split('.');
return new Date(parts[2], parts[1] - 1, parts[0]);
}
function formatDate(d) {
var m = d.getMonth() + 1;
m = m < 10 ? '0' + m : m;
return d.getDate() + '.' + m + '.' + d.getFullYear();
}
var maxdate = parseDate('13.05.2019');
maxdate.setDate(maxdate.getDate() + 60);
console.log(formatDate(maxdate));
// 12.07.2019
Upvotes: 1