javascript - 如何使用 Intl.DateTimeFormat 格式化 JavaScript 日期对象
问题描述
我正在尝试以字符串格式显示日期,就像在 PHP 中所做的那样(使用 date())。
let checkoutDate = new Date();
var formatter = new Intl.DateTimeFormat('en-us', {
weekday: 'long',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3,
hour12: true,
timeZone: 'UTC'
});
console.log(formatter.format(checkoutDate));
输出是:Friday, 3/13/2020, 2:15:03 PM
我如何得到这样的东西:Friday, 13th March 2020
?
解决方案
这是我的版本,您可以使用formatToParts()函数按部分获取它们,假设您每次都将使用相同的格式,然后通过对象数组获取它们,以便您可以创建自己的格式,允许您添加自定义文本. 尽管如果您使用其他日期格式化程序会更容易和更有效。
let checkoutDate = new Date();
var th = 'th';
var formatter = new Intl.DateTimeFormat('en-us', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
fractionalSecondDigits: 3,
timeZone: 'UTC'
});
var formatted = formatter.formatToParts(checkoutDate);
var day = formatted[4].value;
var wr = checker(day);
console.log(wr);
console.log(formatted[0].value+ ',', day +wr, formatted[2].value, formatted[6].value);
function checker(x){
if (x > 3 && x < 21) return 'th';
switch (x % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
//output Friday, 13th March 2020
推荐阅读
- apache-spark - 带有结构化流 protobuf 的 Apache Kafka
- java - 实现 Iterable 与实现 Iterator
- c - 将文件的每一行作为字符串存储在数组中
- sql-server-2012 - SQL“组”和“计数”类别
- encoding - 在 Jest 测试中编码的双引号
- python - 使用“scrapy”进行 Python 网络抓取:不从 span 中提取文本
- javascript - 在 GraphQL 的根部解析自定义类型
- javascript - 如何在 CSS/Javascript 中制作像素化的非直线边框?
- azure - 将智能合约从 remix 部署到 azure 区块链的问题 - 错误
- google-maps - 向上滚动时映射重叠的 AppBar