-4

I am getting dates from an API in one of these formats "mm-dd-yyyy" or "mm/dd/yyyy" also these are in string and I want to parse them from string to js date object

so when I do new Date('12/07/2021') or new Date('12-07-2021') I get the output date which has one day previous 2021-12-06T18:30:00:000Z.

But if I pass the date in yyyy-mm-dd format like this new Date('2021-12-07') then I get correct date as output 2021-12-07T00:00:00.000Z I am facing this issue in the backend with node js.

possible solution according to me is converting the string from mm-dd-yyyy to yyyy-mm-dd format. But how do I do this ?

NOTE: : I cant use moment js as this is a new project and due to moment js depreciation

Roh1
  • 43
  • 1
  • 7

1 Answers1

0

There are UTC variants of setDay, setMonth, setYear that should do what your after.

eg..

function mdyToDate(date) {
  const s = date.split(/[/-]/);
  const [m, d, y] = s.map(v => parseInt(v));
  const ret = new Date('2000-01-01');
  ret.setUTCFullYear(y);
  ret.setUTCMonth(m-1); //months are 0 based
  ret.setUTCDate(d);
  return ret;
}

console.log(mdyToDate('12/07/2021'));
console.log(mdyToDate('12-07-2021'));
console.log(mdyToDate('12/7-2021'));
Keith
  • 22,005
  • 2
  • 27
  • 44