javascript - 将 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”的新时间戳?
谢谢你的帮助!
解决方案
您必须包含几个扩展库,以便 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-节点
推荐阅读
- python - 如何在隐藏 ID 的页面上用 selenium 填充用户名和密码?
- r - 识别子图 plotly click_event
- python - Flask - Jinja2 不在表单输入中呈现占位符(变量)
- python - 使用列表推导中的另外 2 个类属性定义 Python 类属性
- openssl - 如何配置客户端-服务器openssl
- javascript - Node + create-react-app + Express - 如何将函数导入 Express
- c# - 无法将列表发送给邮递员
- python - ModuleNotFoundError - 在 Pycharm intellisense 中找到模块,但在执行程序时没有
- php - 如果按顺序排列,URL 参数不起作用接受
- c++ - 您将如何使此代码自我修改以保存所有输入的密码?