【问题标题】:How to convert utc timezone to specific time zone by dayjs?如何通过dayjs将utc时区转换为特定时区?
【发布时间】:2022-11-30 08:43:14
【问题描述】:
我有 UTC 时区 DateTime 2022-11-28T23:58:29.670Z
并希望获得 DateTime 2022-11-29T03:58:29.670Z + 4 小时。
最后,我需要2022-11-29
我尝试了几种方法
创建时间为 2022-11-28T23:58:29.670Z
const tz = 'America/Santo_Domingo';
const withtz = dayjs(createdAt).tz(tz);
const withtzday = withtz.format('YYYY-MM-DD');
以及补充说明。用户保存一个项目,我将其存储在 UTC 中。但是这个项目应该出现在这个分支的特定时区。因此,当我按天过滤时,我需要按 createdBy 过滤,但按特定时区过滤。
【问题讨论】:
标签:
javascript
datetime
timezone
momentjs
dayjs
【解决方案1】:
我无法重现该问题。在 Dayjs documentation 之后输出正确的 UTC 时间和圣多明各时间。
但是,这个问题似乎假设 Santo Domingo 实际上是 UTC-4 时是 UTC+4。所以小时计算是:当天23:58 - 4:00 = 19:58。这个计算与 Dayjs 的输出匹配。
片段
let createdAt = '2022-11-28T23:58:29.670Z';
const tz = 'America/Santo_Domingo';
let utcdate = dayjs(createdAt);
const tzdate = utcdate.tz(tz);
console.log(
'Created UTC: ', utcdate.toISOString(),
'
Santo Domingo:', tzdate.format('YYYY-MM-DDTHH:mm:ss'),
'
Santo Domingo:', tzdate.format('YYYY-MM-DD')
);
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/utc.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/timezone.js"></script>
<script>
dayjs.extend(window.dayjs_plugin_utc);
dayjs.extend(window.dayjs_plugin_timezone);
</script>