Search code examples
node.jstimezonedate-fns

date-fns convert utc to timezone


I'm trying to parse a utc time to timezone using date-fns in Nodejs

    const date = new Date('2018-09-01T16:01:36.386Z');
    const timeZone = 'Europe/Berlin';
    const zonedDate = utcToZonedTime(date, timeZone);
    // zonedDate could be used to initialize a date picker or display the formatted local date/time

    // Set the output to "1.9.2018 18:01:36.386 GMT+02:00 (CEST)"
    const pattern = "d.M.yyyy HH:mm:ss.SSS 'GMT' XXX (z)";
    const output = format(zonedDate, pattern, { timeZone: 'Europe/Berlin' });
    console.log(output);

I'm using this code from document to check for my problem but it does not print as the document say. Here is the output:

1.9.2018 18:01:36.386 GMT Z (GMT+0)

I don't know why time part is changed but the timezone is still the UTC. It should be:

1.9.2018 18:01:36.386 GMT+02:00 (CEST)

Note: I just use this sample code to show my problem

Node 14.16.0
date-fns: 2.21.3
date-fns-tz: 1.1.4


Solution

  • It's my fault for not checking the import statement. It's must be

    import { format } from 'date-fns-tz';
    

    I used this:

    import { format } from 'date-fns';
    

    It was a little bit confusing when using auto-import on vscode.