我正在使用带有一些日期和时间选项的 IntlDateTimeFormat
。但是,最后我很难获得我想要的格式。
下面是我目前拥有的代码。我想要的结果是返回具有以下格式的字符串:
2022 年 9 月 27 日中午 12:20
到目前为止,当前代码正在返回:
2022 年 9 月 27 日 12:20
注意缺少AM/PM
(大写也很好)
public dateOptions = {
month: 'short',
year: 'numeric',
day: '2-digit',
} as const;
public timeOptions = {
hour: 'numeric',
minute: 'numeric',
dayPeriod: 'narrow',
} as const;
private newDateString() {
const now = new Date();
const tz = Intl.DateTimeFormat().resolvedOptions().locale;
const date = Intl.DateTimeFormat(tz, this.dateOptions).format(now);
const time = Intl.DateTimeFormat(tz, this.timeOptions).format(now);
return `${date}` + ' at ' + `${time}`;
}
最佳答案
dayPeriod: 'narrow'用于“早上”、“上午”、“中午”、“n”等日期的格式样式,将其更改为 hour12: true
dateOptions = {
day: '2-digit',
year: 'numeric',
month: 'short',
}
timeOptions = {
hour: 'numeric',
minute: 'numeric',
hour12: true
//dayPeriod: 'narrow',
}
function newDateString(tz) {
const now = new Date();
//const tz = Intl.DateTimeFormat().resolvedOptions().locale;
const date = Intl.DateTimeFormat(tz, this.dateOptions).format(now);
const time = Intl.DateTimeFormat(tz, this.timeOptions).format(now);
return `${date} at ${time}`;
}
function justAnExampleAsTheOpWatnsThis() {
const now = new Date();
const date = Intl.DateTimeFormat("en-GB", this.dateOptions).format(now);
const time = Intl.DateTimeFormat("en-US", this.timeOptions).format(now);
return `${date} at ${time}`;
}
console.log(newDateString("en-US"));
console.log(newDateString("en-GB"));
console.log("Op want this :" + justAnExampleAsTheOpWatnsThis());
关于javascript - 使用 IntlDateTimeFormat 返回 AM/PM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73867003/