Time Conversion Hacker Rank Problem Solution

In this HackerRank Time Conversion problem solution given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note: – 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.

– 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

Example

s = ’12:01:00PM’

Return ’12:01:00′.

s = ’12:01:00AM’

Return ’00:01:00′.

Function Description

Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.

timeConversion has the following parameter(s):

string s: a time in 24 hour format

Returns

string: the time in 24 hour format

Input Format

A single string s that represents a time in 12-hour clock format (i.e.:hh:mm:ssAM or hh:mm:ssPM).

Constraints

All input times are valid

Time Conversion Hacker Rank Problem Solution JavaScript

function timeConversion(s){
let hour = s.slice(0, 2);
const stringTime = s.slice(-2);
const inBetween = s.slice(2, -2);

let intNum = parseInt(hour);
let time = "";

if(hour != "12" && stringTime == "PM"){
intNum = 12 + intNum;
hour = String(intNum)
}
if(hour == "12" && stringTime == "AM"){
hour = "00";
}
time = hour + inBetween;

return time;
}

Time Conversion Hacker Rank Problem Solution Python

def timeConversion(s):
    hour = s[0:2]
    rest = s[2:-2]
    if s[-2:] == 'PM':
        if int(hour) == 12:
            return hour+rest
        else:
            hour = str(int(hour) + 12)
            return hour+rest
    elif int(hour) == 12 and s[-2:] == 'AM':
        hour = '00'
        return hour+rest
    else:
        return hour+rest

Leave a Comment