Reputation: 3
How can I make this : "08:30AM-09:30AM" into this : "20:30-21:30" Thank you! Its Sentence (String Value)
Upvotes: 0
Views: 30
Reputation: 3839
You can use the moment
library to solve your problem.
You can specify time to the moment constructor and then use the format option.
Example :
const time = "08:30PM-09:30PM"
const times = time.split('-')
const newTimes = times.map(t => moment(t, ["h:mm A"]).format("HH:mm"))
console.log(newTimes.join('-'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
Upvotes: 0
Reputation: 265
I think you mean "08:30PM-09:30PM" into "20:30-21:30"
function to24Hours(time){
let hours = time.substr(0,2);
let minutes = time.substr(3,2);
let AMorPm = time.substr(5,2);
if(AMorPm ==="PM"){
let PMhour = parseInt(hours) + 12
let h = PMhour === 24 ? "12" : String(PMhour)
return `${h.padStart(0,2)}:${minutes}`
}
let AMhour = hours === "12" ? "00" : hours
return `${AMhour}:${minutes}`
}
function to24HoursRange(timeRange){
const [time1, time2] = timeRange.split("-")
return to24Hours(time1) + "-" + to24Hours(time2)
}
console.log(to24HoursRange("08:30PM-09:30PM"))
Upvotes: 1