Time Conversion

  • + 0 comments

    JavaScript

    function timeConversion(s) {
      // spit the time string into 3 parts
      // extract the letters from the 3rd part
      // in the 1st part, add 12 if its PM, and subtract 12 if its 12 pm
      // concatenate everything together
    
      const arr = s.split(":");
      const firstPart = arr[0];
      const secondPart = arr[1];
      const thirdPart = arr[2];
      const id = thirdPart.slice(-2);
    
      let newFirstPart = "";
      if (Number(firstPart) < 12 && id === "AM") {
        newFirstPart = firstPart;
      } else if (Number(firstPart) < 12 && id === "PM") {
        newFirstPart = formatTwoDigits(Number(firstPart) + 12);
      } else if (Number(firstPart) === 12 && id === "AM") {
        newFirstPart = formatTwoDigits(0);
      } else if (Number(firstPart) === 12 && id === "PM") {
        newFirstPart = firstPart;
      }
    
      return newFirstPart + ":" + secondPart + ":" + thirdPart.slice(0, 2);
    }
    

    function formatTwoDigits(num) { return num < 10 ? "0" + num : num; }