nagy.zsolt.hun
nagy.zsolt.hun

Reputation: 6694

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?

Upvotes: 14

Views: 20666

Answers (2)

Simon B.
Simon B.

Reputation: 2706

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.

Upvotes: 6

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241633

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.

Upvotes: 9

Related Questions