[英]Formatting date with EJS/Node.js
I have a string with the following format:我有一个格式如下的字符串:
2020-05-01T23:59:59
And I'd like the output to be formatted like so:我希望 output 的格式如下:
May 1, 2020 - 11:15pm
But I'm finding all kinds of conflicting info and nothing seems to be working.但我发现各种相互矛盾的信息,似乎没有任何效果。
Here, you have two options:在这里,您有两个选择:
The first, and probably easier of the two options is to use a library like moment.js , which can easily achieve this like so:第一个,也可能是这两个选项中更简单的一个是使用像moment.js这样的库,它可以像这样轻松地实现这一点:
moment().format("MMM D, YYYY - hh:mma")
// Should produce May 1, 2020 - 11:15pm
Or, if you must use vanilla JS, or are reluctant to install another package, you can do the following:或者,如果您必须使用 vanilla JS,或者不愿意安装另一个 package,您可以执行以下操作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.