DEV Community


Posted on

Solve UK time changes (DST) with NodeJS and date-fns and Docker (epoch/unix format)

DST time changes can wreck havoc when in the UK time-zone, where you'll find your times might be one hour behind, especially when using epoch/unix format to save your timestamps.

When using NodeJS with date-fns in a docker container, this simple guide will show how to fix the issue.

new Date(); might return a time in GMT as compared to DST. Furthermore, using getUnixTime() from date-fns will return an epoch timestamp which will be in GMT. Converting this back to BST may present a challenge.

const { getUnixTime, format } = require("date-fns");

const date = new Date();
console.log('new Date() print',date, '\n');

const unixTime = getUnixTime(date);

const formatted = format(new Date(unixTime * 1000), 'h:mm aa', {
    timeZone: 'Europe/London',
console.log('formatted timestamp with timezone', formatted);

Enter fullscreen mode Exit fullscreen mode

Running the above code will give you a timestamp which takes DST into account for correct BST as shown by this screenshot from terminal.

Image description

You may be wondering about the unixTime * 1000. This is because date-fns getUnixTime() gives a unix timestamp without milliseconds, and hence converts to seconds.

The date-fns format() function accepts a third parameter for time-zone which is why we have used { timeZone: 'Europe/London', }.

If running in a docker container and it still returns a GMT timestamp, then adding - TZ=Europe/London as part of the environment section of your docker-compose file will help solve the issue by setting the container time-zone to London. Example below:

    build: ./test
    image: ....
      - ....
      - "1234:1234" # http
      - "1234:1234" # debug
      - ....
      - ....
      - ....
      - PORT=....
      - TZ=Europe/London
    command: ....
Enter fullscreen mode Exit fullscreen mode

Top comments (0)