转换 moment.js 中 isoDate 中的日期时间和偏移。

huangapple go评论54阅读模式
英文:

Convert datetime and offset in isoDate in moment.js

问题

在API响应中,我得到了日期、时间和偏移量这三个列。我想要获得ISO日期,但日期和时间的值不应更改。

const date = "2019-04-15"
const time = "13:45"
const offset = 1 // 它也可以是负数,如-4或-5

输出应为"2019-04-15T13:45:00+01:00",在这里你可以看到日期、时间和偏移量都相同。

如果对于相同的日期时间,偏移量为-4,输出应为"2019-04-15T13:45:00-04:00"。

我正在使用以下代码来实现这一点:

moment(date + 'T' + time).utcOffset(offset).format();

但是我得到的是"2019-04-15T12:45:00+01:00",因为它根据偏移值调整了时间,而我不需要这样。

英文:

In the api response I am getting Date, Time and Offset in three columns. I want to get ISOdate but date and time values should not change.

const date="2019-04-15"
const time = "13:45"
const offset = 1 // It can be minus also -4 or -5

Output should be "2019-04-15T13:45:00+01:00" // Here you can see date, time and offset are same

If for same datetime offset is -4 then output should be "2019-04-15T13:45:00-04:00".

I am using this code to achieve that:

moment(date+'T'+time).utcOffset(offset).format();

But I am getting "2019-04-15T12:45:00+01:00" as it is adjusting time by offset value, which I do not require.

答案1

得分: 1

根据文档,在utcOffset()中,您可以使用第二个参数true来相对于本地时间而不是通用时间进行偏移:

传递true将保持相同的本地时间,但以选择通用时间中的不同点为代价。

使用这取决于您的原始时间是如何存储的。如果是UTC时间,并且计算的偏移是相对于UTC的,那么不需要它。但如果偏移是相对于本地服务器时间的,那么您可以使用此附加参数来维护预期的相对值。

英文:

According to the documentation, in the utcOffset() you can use true as a second parameter to offset relative to a local time versus a universal time:

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

Usage of this depends on how your original time is stored. If it is UTC, and calculated offset is relative to UTC, then it is not needed. But in the event the offset is relative to local server time, then you can use this additional parameter to maintain the expected relative value.

huangapple
  • 本文由 发表于 2023年3月31日 02:04:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定