javascript - Moment js time zone date conversion issue
问题描述
I am using moment js to convert user system time to user specified time zone as per his preference. User system time zone is IST and he is specifing a different time zone. For setting the same I am using
moment.tz.setDefault("Pacific/Pago_Pago");
But in one of the scenario I am getting different dates. If I do
moment().startOf('day')
I am getting today's date as Thu Oct 28 2021 00:00:00 GMT+0530 (India Standard Time), But if I am doing
moment(endDate).startOf('day')
I am getting Thu Oct 27 2021 00:00:00 GMT+0530 (India Standard Time) Where end date is the result of last statement i.e. Thu Oct 28 2021 00:00:00 GMT+0530 (India Standard Time)
What I am doing wrong here.
解决方案
创建时刻对象时使用的时区保留为对象的一部分,并用于后续处理。如果在创建初始时刻对象后更改默认时区,则会发生所描述的效果。
例如
// Set default to IST (+5:30)
moment.tz.setDefault('Asia/Kolkata');
// Create initial moment using default timezone
let start = moment().startOf('day');
// Changing the default here doesn't affect above moment
moment.tz.setDefault('Pacific/Pago_Pago');
// This still uses the initial +5:30 offset, not -11:00 for Pago Pago
let timestamp = start.toString();
// This uses the timestamp for the original timezone, but
// then gets start of day in new default timezone
let end = moment(timestamp).startOf('day');
console.log( `Start: ${start.toString()}\nEnd : ${end.toString()}` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data-10-year-range.js"></script>
推荐阅读
- python - 从 metric_learning LMNN 算法中恢复变换矩阵
- html - 在 HTML 应用程序 (.hta) 文件中编码 .ico
- javascript - 使用聚合管道在 MongoDB 中将功能从一个集合添加到另一个集合
- node.js - Node.js 3rd 方 REST API 调用
- c# - 如何使用 Appium 执行双击
- mongodb - Azure CosmosDB - 更新属性名称
- git - 杀死 git push 进程,丢失所有文件
- python - 如何解决 Hangman Game 中的单词生成错误?
- json - Hapi 响应不显示树状(嵌套)json
- arrays - 如何为 for 循环中创建的每个对象创建单独的 UUID?