I have a dateTime string: "2022-02-03T18:40:00.000Z"
I want to convert this into 6:40 PM. How would I go about doing something like that?
I would usually recommend using a date library for date manipulation and formatting, but this can be done quite easily without one as well.
const date = new Date("2022-02-03T18:40:00.000Z");
const convert = (date) => {
const str = (date.getHours() < 12 || date.getHours() === 24) ? "AM" : "PM";
const hours = date.getHours() % 12 || 12;
return `${hours}:${date.getMinutes()}${str}`;
}
console.log(convert(date));
or using toLocaleString with en-us formatting.
const date = new Date("2022-02-03T18:40:00.000Z");
const convert = (date) => {
return date.toLocaleTimeString(
'en-US',
{timeZone: 'UTC', hour12: true, hour: 'numeric', minute: 'numeric'}
);
}
console.log(convert(date));