Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading