简体   繁体   English

将格式化的日期字符串更新为 UTC 值

[英]Update formatted date string to UTC value

Users are able to submit only the date part of a date stamp eg 2020-12-01 , assuming that the time will be 00:00:00假设时间为00:00:00 ,用户只能提交日期戳的日期部分,例如2020-12-01

So, if I have the above value, I want to update the time to its UTC value.因此,如果我有上述值,我想将时间更新为其 UTC 值。 So if I am in the EST timezone, I want to convert 2020-12-01 to 2020-12-01 05:00:00 to account for the five hour offset.因此,如果我在 EST 时区,我想将2020-12-01转换为2020-12-01 05:00:00以考虑五个小时的偏移。

Can I do this with date-fns-tz ?我可以用date-fns-tz做到这一点吗?

const { zonedTimeToUtc, format } = require("date-fns-tz");

const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;

const utcDate = zonedTimeToUtc(new Date("2020-12-01"), tz);

document.getElementById("app").innerHTML = `${format(
  utcDate,
  "yyyy-MM-dd HH:mm:ss"
)}
`;

The above yields 2020-11-30 19:00:00 , which is moving the time 5 hours in the wrong direction.以上产生2020-11-30 19:00:00 ,这将时间向错误的方向移动 5 小时。

https://codesandbox.io/s/happy-hoover-dn417?file=/src/index.js:23-301 https://codesandbox.io/s/happy-hoover-dn417?file=/src/index.js:23-301

Given:鉴于:

const utcDate = zonedTimeToUtc(new Date("2020-12-01"), tz);

The built–in parser will be used to parse the string, so it will be parsed as UTC, then date-fns will apply the offset for the tz .内置解析器将用于解析字符串,因此它将被解析为 UTC,然后 date-fns 将应用tz的偏移量。 Don't do that, use:不要这样做,使用:

const utcDate = zonedTimeToUtc("2020-12-01", tz);

so that date-fns parses the string using the tz .以便 date-fns 使用tz解析字符串。 Now utcDate.toISOString() produces "2020-12-01T05:00:00.000Z", which is the equivalent UTC date and time where tz is America/New_York.现在utcDate.toISOString()生成“2020-12-01T05:00:00.000Z”,这是等效的 UTC 日期和时间,其中tz是 America/New_York。

Date-fns seems to always use the host timezone offset for output, the timeZone option just changes the text offset, it doesn't modify the actual timestamp values. Date-fns 似乎总是使用主机时区偏移量进行输出, timeZone选项只是更改文本偏移量,它不会修改实际的时间戳值。 Likely you have to use utcToZonedTime first to adjust the Date.可能您必须先使用utcToZonedTime来调整日期。 I struggle with date-fns, I find the documentation seriously lacking in useful examples.我与 date-fns 斗争,我发现文档严重缺乏有用的示例。

I'd just use toISOString and remove the "T" and "Z".我只是使用toISOString并删除“T”和“Z”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM