【问题标题】:How to correctly format a postgres timestamp with timezone date using date-fns?如何使用 date-fns 正确格式化带有时区日期的 postgres 时间戳?
【发布时间】:2020-06-15 05:30:21
【问题描述】:

我要从moment 搬到date-fns,需要一些建议。

我有一个postgrestimestamp-with-timezone,我希望将其格式化为MAR 2 AT 1:30 PM

这是我使用 date-fns 的解决方案。

import { format, parseISO } from 'date-fns';

const date = parseISO(message.updated_at); // this is from postgres
const md = format(date, 'MMM d').toUpperCase();
const hm = format(date, 'h:m a');
const formattedTimestamep = `${md} AT ${hm}`;

有没有更正确或更简洁的方式?

【问题讨论】:

  • 您可以执行以下操作 - const formatted = format(date, "MMM d @ h:m a").toUpperCase().replace("@", "AT"),但这并不比您已经在执行的操作“更正确”。

标签: javascript date-fns


【解决方案1】:

我在date-fns github issues 得到了答复。


the docs for format里有一句实用的小句子。

包裹在两个单引号字符 (') 之间的字符被转义。


这导致了这个更简洁的代码版本。

const formattedTimeStamp = format(parseISO(message.updated_at), "MMM d 'AT' h:m a").toUpperCase();

【讨论】:

    猜你喜欢
    • 2015-11-19
    • 2018-01-22
    • 2021-01-29
    • 2021-11-14
    • 2021-01-23
    • 2021-08-03
    • 1970-01-01
    • 2021-10-14
    • 2021-12-06
    相关资源
    最近更新 更多