使用EJS / Node.js格式化日期

问题描述

我有一个具有以下格式的字符串:

2020-05-01T23:59:59

我希望输出的格式如下:

May 1,2020 - 11:15pm

但是我发现各种冲突的信息,而且似乎没有任何作用。

解决方法

在这里,您有两个选择:

两个选项中的第一个,而且可能更容易使用的是使用像moment.js这样的库,它可以像这样轻松实现:

moment().format("MMM D,YYYY - hh:mma")
// Should produce May 1,2020 - 11:15pm

或者,如果必须使用Vanilla JS,或者不愿安装其他软件包,则可以执行以下操作:

const currentDate = new Date();
const dateFormatter = new Intl.DateTimeFormat("en-us",{
  month: "long",day: "numeric",year: "numeric",hour: "numeric",minute: "numeric",hour12: true
});
const dateParts = Object.fromEntries(dateFormatter.formatToParts(currentDate).map(({ type,value }) => [type,value]));

const dateString = `${dateParts.month} ${dateParts.day},${dateParts.year} - ${dateParts.hour}:${dateParts.minute}${dateParts.dayPeriod.toLowerCase()}`;
// dateString should now contain the string May 1,2020 - 11:15pm