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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With