简体   繁体   中英

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

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 confuse when use auto import on vscode.

I'm getting the required output (or very similar), I'm wondering why you see a timezone of GMT Z (GMT+0). It looks to me like something to do with your OS / environment.

const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz')
const os = require('os');

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);

console.log("Node version:", process.version)
console.log("Os:", os.version() + " - " + os.release())

The output I see is:

1.9.2018 18:01:36.386 GMT +02:00 (GMT+2)
Node version: v14.15.5
Os: Windows 10 Pro - 10.0.19041

This is on a windows machine.

Package versions are:

"date-fns": "^2.21.3",
"date-fns-tz": "^1.1.4"

Trying it on Ubuntu (replit.com) I see the following:

1.9.2018 18:01:36.386 GMT +02:00 (GMT+2)
Node version: v12.22.1
Os: #45-Ubuntu SMP Tue Apr 13 01:44:53 UTC 2021 - 5.4.0-1042-gcp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM