I need to format a date with javascript but I'm having a little trouble solving this.
I get two dates, I need to format them and then join the values. On one of the dates I get this:
"2022-07-12T04:00:00-0300"
And on the other date I get this:
"2022-07-12T06:00:00-0300"
These are always dynamic dates returned from my backend, but here on the frontend I need to display these two dates in this following format:
"04:00 - 06:00"
You can use slice() method.
var date1 = "2022-07-12T04:00:00-0300";
var date2 = "2022-07-12T06:00:00-0300";
var formatted = `${date1.slice(11, 16)} - ${date2.slice(11, 16)}`;
console.log(formatted);
This is assuming you only need the hours and minutes.
function datesToRange(start, end) {
if (!start || !end) return ""; // If either date is null or undefined.
return start.substring(12, 17) + " - " + end.substring(12, 17);
}
Now you can call this method to get the range in your required format.
E.g.
datesToRange("2022-07-12T04:00:00-0300", "2022-07-12T06:00:00-0300");
Will return "04:00 - 06:00".