【问题标题】:Format date and time from UTC with offset using date-fns使用 date-fns 格式化来自 UTC 的日期和时间,并带有偏移量
【发布时间】:2021-12-06 17:45:05
【问题描述】:

我有一个 UTC 时间,偏移量如下所示。我正在尝试使用 date-fns 库中的 format 函数格式化 UTC 日期时间字符串。

import { format } from "date-fns";

const utcDateTime = "2021-10-14T21:03:56.3256046+00:00";
const formattedDate = format(new Date(utcDateTime), "MM/dd/yyyy hh:mm");

我期待的是 10/14/2021 21:03,24 小时时间格式,但我得到的是 10/14/2021 04:03,我的时区的转换日期时间。

如何像UTC时间一样显示日期和时间,而不是将日期时间转换为本地时区?

我使用CodeSandbox 创建了一个工作示例。有人可以帮忙吗?

【问题讨论】:

标签: javascript date datetime date-fns


【解决方案1】:

花了很多时间后,我能够使用纯 JavaScript Date 对象及其函数来达到预期的效果。

  • 首先,解析日期时间字符串,并使用toISOString()函数将其转换为ISO字符串。

  • 其次,将格式化的日期和时间从 ISO 字符串中提取出来。

下面是代码

const formatToUTCDateTime = (dateString) => {
  const date = new Date(Date.parse(dateString));
  const formattedDate = date.toISOString().split("T")[0].split("-");
  const formattedTime = date.toISOString().split("T")[1].split(":");
  return `${formattedDate[1]}/${formattedDate[2]}/${formattedDate[0]} ${formattedTime[0]}:${formattedTime[1]}`;
};

console.log("Result - ", formatToUTCDateTime("2021-10-14T20:03:56.3256046+00:00"));

【讨论】:

  • new Date("2021-10-14T21:03:56.3256046+00:00").toLocaleString('en-US',{hour12: false, timeZone:'UTC'}).slice(0,-3),其中 slice 去掉了秒组件。但是对于不支持的格式使用内置解析器时要小心,秒上额外的 4 位精度可能对某些实现来说是个问题。或不。还要注意美国格式的日期,世界上绝大多数人都觉得它令人困惑,最好使用带有月份名称或缩写的明确格式,例如“Oct 14, 2021 21:03”。
猜你喜欢
  • 2021-11-14
  • 2021-01-23
  • 1970-01-01
  • 2022-11-17
  • 2021-01-29
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
相关资源
最近更新 更多