0

Hi there I would like to convert 'YYYY-M-D' to 'YYYY-MM-DD' with toISOString but when I set one digit DAy it's not quite correct return value.

const date = new Date('1991-1-1').toISOString().substr(0, 10);
//"1990-12-31"

or

const date = new Date('1991-01-01').toISOString().substr(0, 10);

//"1990-12-31"

But I would like to have "1990-01-01", I know that I can use some getMonth and so on, I looking for a native solution and simple one. Thanks

Palaniichuk Dmytro
  • 2,943
  • 12
  • 36
  • 66
  • The second one should work. The *only* way I can get the `1990-12-31` output is if I try this first code in Edge. The second piece of code works in Chrome, Firefox, Edge, and IE11 for me. – VLAZ Oct 18 '19 at 16:20

2 Answers2

0

What about using moment.js?

const date = moment('1991-1-1').format('Y-MM-DD'); // 1991-01-01
jalex19
  • 201
  • 2
  • 7
  • 1
    I know moment, but it's a small app, and only one validation, I font want use library for one operation – Palaniichuk Dmytro Oct 18 '19 at 16:12
  • 1
    what about overriding the locale options? `const date = new Date('1991-1-1');` `date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', });` That will return something like '1991/01/01', then you just play with it, may be changing the '/' by '-' – jalex19 Oct 18 '19 at 16:19
0

"1991-1-1" is not a format supported by ECMAScript so parsing is implementation dependent, it might be parsed as UTC, local or treated as an invalid date. new Date('1991-1-1') returns an invalid date in Safari at least.

If you just want to add a leading zero to single digit numbers, do that and avoid the vagaries of the built–in parser:

// Using split + join
console.log(
  '1991-1-1'.split('-').map(c => (c<10?'0':'') + +c).join('-')
);

// Using replace
console.log(
  '1991-1-1'.replace(/\d+/g, c => (c<10?'0':'') + +c)
);

PS

Safari also incorrectly treats 1991-01-01 as local, not UTC, so for users with a negative timezone offset (positive in EMCAScript) new Date('1991-01-01') returns a date for 1990-12-31. See Why does Date.parse give incorrect results?

If you really must use Date, then manually parse it as UTC and use toISOString. That avoids issues with the built–in parser and timezone offsets.

// Change YYYY-M-D to YYYY-MM-DD
// Separator can be any non-digit character
function reformatDate(s) {
  let [y,m,d] = s.split(/\D/);
  return new Date(Date.UTC(y, m-1, d)).toISOString().slice(0,10);
}

console.log(reformatDate('1991-1-1'));
RobG
  • 142,382
  • 31
  • 172
  • 209