首页 > 解决方案 > 将 unix 时间戳转换为特定时区

问题描述

我在 unix 中有一个时间戳,如下所示,它在+2:00时区中,但我想获得相同的日期,但在+0:00时区中,使用dayjs,

console.log("TIMESTAMP: ", dayjs.unix(timestamp).format());
>  TIMESTAMP:  2021-05-20T13:46:07+02:00

console.log("FIXED TIMESTAMP: ", dayjs.unix(timestamp).tz("Europe/London").format());
>  FIXED TIMESTAMP:  2021-05-20T12:46:07+01:00

上面我尝试这样做,tz("Europe/London")但是,我不知道为什么,我的日期在“+01:00”时区...,为什么这个函数不返回转换为“+0:00”的新时间戳?

谢谢你的帮助!

标签: javascripttypescriptdatetimeunix

解决方案


您必须包含几个扩展库,以便 UTC 和时区格式在 dayjs 中工作。UTC 和时区 Javascript 文件都是必需的。我使用了 1.10.7 版本,因为它们是最新的。

如果您在浏览器中工作,请包括以下来源。HTML:

<script src="https://unpkg.com/dayjs@1.10.7/dayjs.min.js"></script>
<script src="https://unpkg.com/dayjs@1.10.7/plugin/utc.js"></script>
<script src="https://unpkg.com/dayjs@1.10.7/plugin/timezone.js"></script>

JavaScript:

dayjs.extend(window.dayjs_plugin_utc);
dayjs.extend(window.dayjs_plugin_timezone);

let printFormat = 'hh:mm:ssA';
let nowLocal = dayjs().utc().local().format(printFormat);
console.log(nowLocal);
console.log(dayjs().tz("America/New_York").format(printFormat));
console.log(dayjs().tz("Asia/Tokyo").format(printFormat));

对于您的尝试有几点注意事项,“tz”(时区)对象不会挂起 unix() 函数,它直接附加到顶级 dayjs 对象。上面的示例采用本地时间,并以 hh:mm:ssAM|PM 格式在三个不同的时区打印。unix 函数接受一个 Unix 时间戳并返回一个 DayJS 对象。

这是运行上述示例的 JSFiddle: https ://jsfiddle.net/e4x507p3/2/

请注意,如果您在浏览器中使用扩展,这应该可以工作,如果您在 NodeJS 中工作,则需要不同的方法: https ://day.js.org/docs/en/plugin/loading-into-节点


推荐阅读