0

对我来说,以下列格式格式化日期和时间字符串的最佳和干净的方法是什么?

For today:
HH:MM PM/AM
For any time not today:
MM(short string) DD(short string) HH:MM PM/AM
const displayTime = new Date(Date.now()).toLocaleDateString('en-US', {
  month: 'short',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  hour12: true,
});
console.log(displayTime) //=>"May 18, 5:18 PM"

//expected 4:26 PM for today
//expected MAY 1ST(2ND, 3RD, 4TH) 4:26 PM for any day not today
4

1 回答 1

-1

您在正确的轨道上使用toLocaleDateString,但是它不能为今天做一种格式,而在它自己的旧版本中做一种 - 你必须自己滚动它,因为有一些隐含的逻辑 - 你是指今天还是在过去 24 小时?你处理时区吗?未来应该如何处理?等等。

假设你的意思是今天这将是:

const d = dateIWantToFormat;

// Is this date today?
const today = d.toDateString() === new Date().toDateString();

const displayTime = d.toLocaleDateString(
    'en-US', 
    today ? {            // If today just show "HH:MM PM/AM"
      hour: 'numeric',
      minute: 'numeric',
      hour12: true,
    } : 
    {                    // Otherwise show "mmm DD HH:MM PM/AM"
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      hour12: true,
    });
于 2021-05-18T21:37:20.320 回答