首页 > 解决方案 > 使用 EJS/Node.js 格式化日期

问题描述

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

2020-05-01T23:59:59

我希望输出格式如下:

May 1, 2020 - 11:15pm

但我发现各种相互矛盾的信息,似乎没有任何效果。

标签: javascriptnode.jsejs

解决方案


在这里,您有两个选择:

第一个,也可能是这两个选项中更简单的一个是使用像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

推荐阅读