timezones
set container timezone
Set the TZ
environment variable inside linux containers to set the timezone, for example docker run -e TZ={timezone}
or, for example inside your docker-compose
;
environment:
TZ: "Australia/Sydney"
datetime libraries
- tempo
- date-fns
- typescript
- luxon
- javascript / types via
@types/luxon
- adds a
DateTime
object - 4.48mb unpacked
- javascript / types via
- dayjs
- typescript
- extended functionality via plugins
- Broken for daylight savings
- moment.js
- dead
- mutable
- js-joda
- a port from java, including the api 🤢
timezones
dayjs
import dayjs from "dayjs";
import tz from "dayjs/plugin/timezone";
dayjs.extend(tz);
const now = dayjs();
const sydneyDate = dayjs("2025-03-03").tz("Australia/Sydney");
const isToday = now.isSame(sydneyDate, "day");
Intl.DateTimeFormat
const date = new Date("2025-03-03");
const asSydneyTime = date.toLocaleDateString("en-AU", {
timeZone: "Australia/Sydney",
});
vitest
Running tests in multiple time zones
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
workspace: [
{
extends: true,
test: {
name: "GMT",
env: {
TZ: "UTC",
},
},
},
{
extends: true,
test: {
name: "GMT+13",
env: {
TZ: "America/Auckland",
},
},
},
],
},
});
Mocking now & timezones in tests
export const mockNow = (now: string, timeZone?: string) => {
beforeEach(() => {
vi.useFakeTimers();
const date = new Date(now);
vi.setSystemTime(date);
if (timeZone) {
vi.spyOn(globalThis.Intl, "DateTimeFormat").mockImplementation(() => ({
resolvedOptions: () => ({
timeZone, // Your timezone, rest is irrelevant
calendar: "gregory",
locale: "en-AU",
numberingSystem: "latin",
}),
format: () => "1/1/2022",
formatRange: () => "1/1/2022 – 1/1/2023",
formatRangeToParts: () => [],
formatToParts: () => [],
}));
}
});
afterEach(() => {
vi.useRealTimers();
});
};
chrome
Simulate different time zones in Chrome DevTools:
- Open DevTools
- Open Console Drawer (Esc)
- Click on the three dots in the left corner
- Select Sensors
- Enter a Timezone ID like
UTC
orAustralia/Sydney