Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - how to mock timezone?

I have a function that calculates which date (YYYY-MM-DD) a given timestamp resolves to on the users local timezone. E.g.: 2019-12-31T23:30:00.000Z resolves to 2020-01-01 on UTC+1, but resolves to 2019-12-31 on UTC-1.

This is my implementation:

function calcLocalYyyyMmDd(dateStr) {
  const date = new Date(dateStr);
  const year = String(date.getFullYear()).padStart(4, "0");
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

This works as expected, however, I would like to verify this behaviour in a unit test (using jest, not sure if relevant).

describe("calcLocalYyyyMmDd", () => {
  test("calculates correct date on UTC+1", () => {
    // TODO mock local timezone
    const result = calcLocalYyyyMmDd("2019-12-31T23:30:00.000Z");
    expect(result).toBe("2020-01-01");
  });

  test("calculates correct date on UTC-1", () => {
    // TODO mock local timezone
    const result = calcLocalYyyyMmDd("2020-01-01T00:30:00.000Z");
    expect(result).toBe("2019-12-31");
  });
});

How can I mock the local timezone?

like image 222
nagy.zsolt.hun Avatar asked Jan 17 '20 09:01

nagy.zsolt.hun


2 Answers

Unfortunately, there is no simple way to do this.

However, if you are on a Linux system you can set the TZ environment variable before launching a browser or starting Node.js, but once the process is running the time zone cannot be changed. The Date object only uses the system's local time zone.

Note that this approach isn't reliable on Windows due to complexities of time zone implementations.

like image 111
Matt Johnson-Pint Avatar answered Sep 30 '22 13:09

Matt Johnson-Pint


If you're writing jest tests or similar, consider using https://www.npmjs.com/package/timezone-mock to enable testing your code in at least two timezones.

like image 20
Simon B. Avatar answered Sep 30 '22 11:09

Simon B.