簡體   English   中英

date-fns 將 UTC 轉換為時區

[英]date-fns convert utc to timezone

我正在嘗試使用 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);

我正在使用文檔中的此代碼來檢查我的問題,但它沒有像文檔所說的那樣打印。 這是 output:

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

我不知道為什么時間部分會改變,但時區仍然是 UTC。 它應該是:

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

注意:我只是使用此示例代碼來顯示我的問題

節點 14.16.0
日期-fns:2.21.3
日期-fns-tz:1.1.4

沒有檢查導入語句是我的錯。 應該是

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

我用這個:

import { format } from 'date-fns';

在 vscode 上使用自動導入時有點混亂。

我得到了所需的 output(或非常相似),我想知道您為什么看到 GMT Z (GMT+0) 的時區。 在我看來,這與您的操作系統/環境有關。

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

我看到的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

這是在 windows 機器上。

Package 版本為:

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

在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM