I'm using the IntlDateTimeFormat
with some date and time options. However, I'm having difficulties getting the format I want at the end.
Below is the code I currently have. The result I'm after is to return a string with the following formatting:
Sept 27, 2022 at 12:20 PM
So far, the current code is returning:
27 Sept 2022 at 12:20
Note the AM/PM
missing (capitalised would be great too)
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}`;
}
CodePudding user response:
dayPeriod: 'narrow' The formatting style used for day periods like "in the morning", "am", "noon", "n" etc. , change it to 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());
CodePudding user response:
Removed the dayPeriod: 'narrow'
and then add the option to use time in 12-hours format hourCycle: 'h12'
.
dayPeriod: 'narrow'
would format the time in the text format depends on the locale.hourCycle: 'h12' | 'h11' | 'h23' | 'h24'
would format the time in the 12/24 hours format
var dateOptions = {
month: 'short',
year: 'numeric',
day: '2-digit',
};
var timeOptions = {
hour: 'numeric',
minute: 'numeric',
hourCycle: 'h12'
};
function 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);
console.log(`${date}` ' at ' `${time}`);
}
newDateString(new Date())