javascript - 使用 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
推荐阅读
- python - python manage.py 在终端上迁移然后显示错误?
- kotlin - 如何处理地图
以及来自 api 的自定义错误响应 - smartcard - 无法使用 LockHub 在读卡器中注册智能卡
- matlab - 当条件在另一个向量中成立时删除向量中的点
- java - 在 AEM 中以编程方式对 LDAP 用户进行身份验证
- c# - 通过 .Net Core 应用程序中的 PostAsJsonAsync 获取 .Net Core Api 中的值
- android - 日历 UI 未在 Android 上使用 react-native-add-calendar-event 打开
- javascript - 时间递归函数的表现
- python - pandas shift方法创建滞后值有什么问题吗?
- c# - 派生类有导航属性时的外键约束