Home > Back-end >  How do I format this string '8:00-9:00 AM' to a valid ISO time format?
How do I format this string '8:00-9:00 AM' to a valid ISO time format?

Time:09-07

I need to format this string so I cand send it to an angular app using fullcalendar for its calendar, so i can concatenate the start hour of the appointment to the date.

Thank you very much!, this is my first question here...

I've tried to split the string, parse it to number, and then add conditional operators.

CodePudding user response:

Since you do not include a date, your expected format is just hh, but you can add the other dd-mm if you prefer

let timeString = '8 AM'

function to24Hour(timeStr) {
   let spaceIndex = timeStr.indexOf(' ');
   let beforePM = timeStr.split(' ')[1] === 'AM' ? true : false //get if before PM
   timeStr = timeStr.split(' ')[0]; //split at space and return number
    
   if (beforePM) {
      if (timeStr.length === 1) timeStr = '0'   timeStr;
      return timeStr   '-00-00';
   } else {
      return String(12   Number(timeStr))   '-00-00';
   }
}

console.log(to24Hour(timeString));

  • Related