0

I have a typescript project were I was getting an error around new years. I wrote a simple jest test like this:

const a = new Date(2022, 0, 1);
const b = new Date("2022-01-01");
expect(a).toEqual(b);

and I got FAILED because

// a is "Sat Jan 01 2022 00:00:00 GMT+0100 (Central European Standard Time)"
// b is "Sat Jan 01 2022 01:00:00 GMT+0100 (Central European Standard Time)"

see the difference in time?

jest test screenshot

What do I not get? It looks to me like this should not happen. Is there a reason for this? thanks so much for your input! happy new year 2022 :)

aricma
  • 21
  • 1
  • 1
  • 5
  • Constructing Date instances from strings relies on the platform to parse the date string, which is only predictable with standard string formats. – Pointy Jan 01 '22 at 20:11
  • which would be one of those standards? Its not like he is confusing month with day ... he is adding hours which I did not define and the constructor is inconsistently adding them – aricma Jan 01 '22 at 20:20
  • 1
    The only real standard is the ISO date format. Probably what is happening is that one of the dates is being interpreted as a UTC date, and the local time zone where the OP is running the code is one hour *ahead* of UTC. – Pointy Jan 01 '22 at 20:22
  • Also, constructing two separate dates in two separate expressions, even if everything is done properly, may result in two dates that are not equal, because the clock is running while the code is being evaluated. – Pointy Jan 01 '22 at 20:23
  • 2
    `"2022-01-01"` is interpreted as UTC, while `Date(year, month, day)` interprets the given parameters (defaulting to 0 hours, 0 minutes) as local time indicators. – trincot Jan 01 '22 at 20:28
  • yes you are right! time is the problem here ... confusing though. It does not look right when a constructor does 2 things for "the same input". I mean if I do not give him time he should leave the time at 0. What he basically does for "b" but not for "a" for some reason. As a workaround I now wrote a new constructor that only constructs dates without time ... I use the `setHours(0, 0, 0, 0)` method from Date – aricma Jan 01 '22 at 21:57
  • @aricma—the time is zero, UTC. The reason YYYY-MM-DD is parsed as UTC instead of the more logical local is [here on the TC39 message board](https://github.com/tc39/ecma262/issues/87). – RobG Jan 02 '22 at 11:24

0 Answers0