As indicated on MDN, using the Date constructor to parse dates is discouraged because of implementation differences.
However, if you really want to do so, the only solution is to ensure that the inputs you provide are consistent. This will ensure that (at least within a single environment) the outputs will be consistent.
To have both work like 2017-5-19
:
function adjustDateString(str) {
return str.split('-').map(Number).join('-');
}
console.log(new Date(adjustDateString('2017-5-19')))
console.log(new Date(adjustDateString('2017-05-19')))
To have both work like 2017-05-19
:
function padTo2Digits(str) {
return str.length >= 2 ? str : '0' + str;
}
function adjustDateString(str) {
return str.split('-').map(padTo2Digits).join('-');
}
console.log(new Date(adjustDateString('2017-5-19')))
console.log(new Date(adjustDateString('2017-05-19')))
Edit: However, you're probably better off, as I pointed out above, not using the Date
constructor on a string. Just split it into its values and pass those into the constructor:
function parseDate(str) {
var parts = str.split('-').map(Number);
return new Date(parts[0], parts[1], parts[2]);
}
console.log(parseDate('2017-5-19'));
console.log(parseDate('2017-05-19'));
Using array deconstructuring syntax (requires ES6+):
function parseDate(str) {
let [year, month, day] = str.split('-').map(Number);
return new Date(year, month, day);
}
console.log(parseDate('2017-5-19'));
console.log(parseDate('2017-05-19'));