如何使用 date-fns 格式化日期字符串而不进行时区转换?

问题描述 投票:0回答:2

我有非常简单的日期作为 ISO

const mytDate = '2021-10-24T16:00:00.000Z'
的字符串,我想将其格式化为
format(new Date(myDate), 'yyyy-MM-dd HH:mm:ss')
new Date()
因为它会将其转换为我的本地时区,而我不想要它。我想获取这个字符串日期并按原样格式化它。

有解决办法吗?

干杯!

format date-fns
2个回答
0
投票

我没有任何解决方案,所以我为此准备了自定义实用程序:

const getRawDate = (rawDate) => {
  if (!isValid(new Date(rawDate))) {
    return null;
  }

  // Split by T separator in order to take date and time
  const [date, time] = rawDate.split('T');
  // return date and time without timezone indication.
  return `${date} ${time.slice(0, -5)}`;
}


0
投票

在解析为

Z
之前删除结尾
Date
应该会有所帮助。

format(new Date(myDate.replace('Z', '')), 'yyyy-MM-dd HH:mm:ss')
// Outputs 2021-10-24 16:00:00
© www.soinside.com 2019 - 2024. All rights reserved.