Reputation: 853
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
Upvotes: 5
Views: 17835
Reputation: 17854
As of https://github.com/marnusw/date-fns-tz/releases/tag/v3.0.0, zonedTimeToUtc
was renamed to toZonedTime
.
const zonedParsedDate = toZonedTime(parsedDate, "America/New_York");
Upvotes: 4
Reputation: 853
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.
Upvotes: 3
Reputation: 30725
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
Upvotes: 4