Time Conversion

Sort by

recency

|

5143 Discussions

|

  • + 0 comments

    Here's my solution in Java:

    public static String timeConversion(String s) {
        String meridiem = s.substring(8);
        int hours = Integer.parseInt(s.substring(0, 2));
        String colonsMinutesAndSeconds = s.substring(2, 8);
    
        if (meridiem.equals("AM") && hours == 12) {
            hours = 0;
        } else if (meridiem.equals("PM") && hours != 12) {
            hours += 12;
        }
    
        return String.format("%02d%s", hours, colonsMinutesAndSeconds);
    }
    
  • + 0 comments

    My short answer…

    def timeConversion(s):
        return f'{int(s[:2]) % 12 + (0 if s[-2:] == "AM" else 12):02}' + s[2:8]
    
  • + 0 comments

    def timeConversion(s): # Write your code here meridian = s[8:10] print(s[2:7]) hour_given = int(s[0:2]) hour_computed = hour_given%12 if meridian=='AM' else ((hour_given%12)+12) return str(hour_computed).zfill(2)+s[2:8]

  • + 0 comments

    Using datetime tools:

    import os
    import datetime
    
    def timeConversion(s):
        time_format = "%H:%M:%S"
        dt_s = datetime.datetime.strptime(s, "%I:%M:%S%p")
        return datetime.datetime.strftime(dt_s, time_format)
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        s = input()
        result = timeConversion(s)
    
        fptr.write(result + '\n')
        fptr.close()
    
  • + 0 comments

    JavaScript

    function timeConversion(s) {

    let [hours, minutes, seconds] = s.split(':');
    
    if (hours === '12'){
        hours = '00';
    }
    
    if (seconds.indexOf('PM')  != -1 && hours < 12 ){
        hours = parseInt(hours, 10) + 12;
    }
    
    let conversion = ``${hours}:$`{minutes}:${seconds}`
    
    return conversion.slice(0, -2);
    

    }