I'm trying to use Javascript for formatting the time to a localized format using Intl.DateTimeFormat method.
I have several instances of time strings in 24h format i want to localize in a HTML page, for example:
<span class="timeclass">18:45</span> //and so on..
And i am able to format the time with the following code, which uses a Date object:
let locale = 'en-US'; // this variable changes, example 'en-UK', etc
let time = new Date('1971-12-12T18:45');
console.log(new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: 'numeric',
}).format(time)); //output is "6:45 PM"
As the code shows, i added a dummy date in order for the Date object to be semantically correct. Now, i'm trying to write a function to replace all instances of times contained within timeelem classes:
var locale = 'en-US';
var timeformat = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: 'numeric',
});
timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
timeelements.textContent= timeformat.format(timeelements.textContent);
});
But it is not working because it is getting the time in the format 18:45 instead of 1971-12-12T18:45. What is the best way to prepend such dummy date to the string? The date is only relevant for the localization function to work, by the way.
textContentinstead ofinnerHTML. In fact, avoid usinginnerHTMLentirely because that's how you get XSS vulnerabilities.