how to make day.js format a date in non-system timezone?

24 Views Asked by At

I need to format a date represented in seconds as an ISO formatted string in my time zone 'Europe/Berlin'. So I can't use .toISOString().

everything is working fine on my machine, but our build pipeline is running on a server in a different time zone. And this causes an error in our tests. Which also means that I can't debug it.

here is the method I want to test:

public secondsToString(seconds: number) {
    dayjs.tz.setDefault('Europe/Berlin');
    return dayjs(seconds * 1000, 'Europe/Berlin').format();
}

I know this is a bad place to set the default time zone, but I tried narrowing down the error. And here is the test:

describe('secondsToString', () => {
    it('works', () => {
        const seconds = 1704067200;
        const expected = '2024-01-01T01:00:00+01:00';
        const actual = component.secondsToString(seconds);
        expect(actual).toEqual(expected);
    });
});

as I said, it works on my local machine. But in our test pipeline, I get the error:

Chrome Headless 120.0.6099.224 (Linux x86_64) ComparisonGraphComponent secondsToString works FAILED
Expected '2024-01-01T00:00:00+00:00' to equal '2024-01-01T01:00:00+01:00'.
    at <Jasmine>
    at UserContext.apply (src/app/intra-day-quotes/comparison-graph/comparison-graph.component.spec.ts:210:28)
    at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:368:26)
    at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:273:39)
    at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:367:52)

Why does day.js convert the date to UTC before formatting? And how can I prevent that?

0

There are 0 best solutions below