gpt4 book ai didi

javascript - 设置日期的年、月、日、时、分、秒和 UTC 偏移值

转载 作者:行者123 更新时间:2023-11-28 03:47:09 28 4
gpt4 key购买 nike

如果我有以下值:

const year = 1890
const month = 6
const day = 1
const hour = 5
const minute = 50
const second = 0
const utcOffset = -10

如何设置 Javascript 日期或 momentJS 日期1890 年 6 月 1 日 5:50(早上),UTC 偏移量为 -10?

我在互联网上看到的都是例子新日期(年、月、日、小时、分钟、秒、毫秒)。默认为您本地的时区,但我想使用 +8.5 代表 +8.5 GMT 等数字手动设置时区。

如何为 Date 或 Moment JS 执行此操作?

最佳答案

您可以使用时刻utcOffset :

Setting the UTC offset by supplying minutes. Note that once you set an offset, it's fixed and won't change on its own (i.e there are no DST rules). If you want an actual time zone -- time in a particular location, like America/Los_Angeles, consider moment-timezone.

在您的情况下,您可以传递 true 作为第二个参数,以使其保留一天中的时间:

The utcOffset function has an optional second parameter which accepts a boolean value indicating whether to keep the existing time of day.

  • Passing false (the default) will keep the same instant in Universal Time, but the local time will change.

  • Passing true will keep the same local time, but at the expense of choosing a different point in Universal Time.

One use of this feature is if you want to construct a moment with a specific time zone offset using only numeric input values

这是一个实时示例:

const year = 1890
const month = 6
const day = 1
const hour = 5
const minute = 50
const second = 0
const utcOffset = -10

let m = moment([year, month-1, day, hour, minute, second]).utcOffset(utcOffset, true)

console.log(m.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

请记住,月份的索引为 0。

关于javascript - 设置日期的年、月、日、时、分、秒和 UTC 偏移值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48356736/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com