[英]date-fns convert utc to timezone
I'm trying to parse a utc time to timezone using date-fns in Nodejs我正在尝试使用 Nodejs 中的 date-fns 将 utc 时间解析为时区
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:
这是 output:
1.9.2018 18:01:36.386 GMT Z (GMT+0)
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.我不知道为什么时间部分会改变,但时区仍然是 UTC。 It should be:
它应该是:
1.9.2018 18:01:36.386 GMT+02:00 (CEST)
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节点 14.16.0
date-fns: 2.21.3日期-fns:2.21.3
date-fns-tz: 1.1.4日期-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.在 vscode 上使用自动导入时有点混乱。
I'm getting the required output (or very similar), I'm wondering why you see a timezone of GMT Z (GMT+0).我得到了所需的 output(或非常相似),我想知道您为什么看到 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:我看到的output是:
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.这是在 windows 机器上。
Package versions are: Package 版本为:
"date-fns": "^2.21.3",
"date-fns-tz": "^1.1.4"
Trying it on Ubuntu (replit.com) I see the following:在 Ubuntu (replit.com) 上试用它,我看到以下内容:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.