Javascript date is different from month format

While debugging my application, I found something strange:

new Date('2017-5-19')  -> Fri May 19 2017 00:00:00 GMT+0300 (FLE Summer Time)
new Date('2017-05-19') -> Fri May 19 2017 03:00:00 GMT+0300 (FLE Summer Time)

      

I am setting the date from a String for example '2017-5-19'

, but when the number is zero to month, the date is nonzero.

How can I achieve the same result with inputs 5

and 05

?

ps I have to maintain strict regime

+3


source to share


1 answer


As stated on MDN , using the Date constructor to parse dates is deprecated due to implementation differences.

However, if you really want to, the only solution is to ensure that the inputs you provide are consistent. This ensures that (in at least one environment) the outputs are consistent.

To make 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')))
      

Run code


To make 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')))
      

Run code


Edit: However, you are probably better off, as I said above, not to use the inline constructor Date

. Just split it by your values ​​and pass them to 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'));
      

Run code


Using array deconstruction syntax (ES6 + required):



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'));
      

Run code


+3


source







All Articles