Time Conversion

Sort by

recency

|

839 Discussions

|

  • + 0 comments
        const am: number = s.search("AM")
        const pm: number = s.search("PM")
        const timeText: string[] = s.split(":")
        
        if (am > 0) {
            if (timeText[0] === "12") {
                return "00:"+timeText[1]+":"+timeText[2].slice(0,2)
            }else {
                return s.slice(0, am)
            }
        } else if (pm > 0) {
            return (timeText[0] === "12" ? timeText[0] : parseInt(timeText[0])+12)+":"+timeText[1]+":"+timeText[2].slice(0,2)
        }
    
  • + 0 comments
    from datetime import datetime
    #
    # Complete the 'timeConversion' function below.
    #
    # The function is expected to return a STRING.
    # The function accepts STRING s as parameter.
    #
    
    def timeConversion(s):
        # Write your code here
        time_obj = datetime.strptime(s,'%I:%M:%S%p')
        return time_obj.strftime('%H:%M:%S')
       
    
  • + 0 comments

    Why doesn't this work?

    function timeConversion(s: string): string {
        // Write your code here
        const date: Date = new Date(`10/27/2024 ${s}`)
        const dateString: string = date.toLocaleTimeString("en-us", { hour12: false })
        return dateString
    }
    

    Can we not utilize date objects for this? I think it makes it more robust TBH

  • + 0 comments

    python3 solution using modulo:

    def timeConversion(s):
        
        if s[-2:] == 'AM':
            h = int(s[0:2]) % 12
        else:
            h = int(s[0:2]) % 12 + 12
        
        h = '0' + str(h) if h < 12 else str(h)
        return h + s[2:6] + s[6:8]
    
  • + 0 comments

    public static String timeConversion(String s) { int n = s.length(); String period = s.substring(n - 2); // Extract AM or PM int hour = Integer.parseInt(s.substring(0, 2)); // Extract hour part String minAndSec = s.substring(2, n - 2); // Extract minutes and seconds

        // Convert the hour based on the period (AM/PM)
        if (period.equals("AM")) {
            if (hour == 12) {
                hour = 0;  // Midnight case: 12 AM -> 00 in 24-hour format
            }
        } else {
            if (hour != 12) {
                hour += 12;  // Afternoon/evening case: convert PM hour to 24-hour format
            }
        }
    
        // Format and return the converted time
        return String.format("%02d%s", hour, minAndSec);
    }
    

    }