Time Conversion

Sort by

recency

|

5126 Discussions

|

  • + 0 comments

    Python solution O(1) time O(1) space:

    def timeConversion(s):
        period = s[-2:]
        time = s[:-2].split(':')
    
        hh = int(time[0])
        
        if period == "AM" and hh == 12:
            hh = 0
        
        if period == "PM" and hh != 12:
            hh += 12
    
        return f"{hh:02d}:{time[1]}:{time[2]}"
    
  • + 0 comments
    function timeConversion(s) {
        const AMPM = s.slice(-2);
        const hours = s.slice(0, 2);
        
        if ((AMPM == "AM" && hours < 12) || (AMPM == "PM" && hours == 12)) {
            return s.substring(0, s.length - 2);
        }
        if (AMPM == "AM" && hours == 12) {
            return '00' + s.substring(2, s.length - 2);
        }
        return +hours + 12 + s.substring(2, s.length - 2);
    }
    
  • + 0 comments

    Here is problem solution in Python, java, C++, C and Javascript - https://programmingoneonone.com/hackerrank-time-conversion-problem-solution.html

  • + 0 comments

    TypeScript

    function timeConversion(s: string): string {
        const period = s.slice(-2);
        let [hh, mm, ss] = s.slice(0, -2).split(':');
        
        if (period === 'PM' && hh !== '12') {
            hh = (parseInt(hh, 10) + 12).toString();
        } else if (period === 'AM' && hh === '12') {
            hh = '00';
        }
        
        hh = hh.padStart(2, '0');
        
        return `${hh}:${mm}:${ss}`;
    }
    
    const s = require("fs").readFileSync(0, 'utf-8').trim();
    console.log(timeConversion(s));
    
  • + 0 comments
    std::string time_conversion(std::string s){
        if(s[8] == 'A'){
            return s.substr(0,2) == "12" ?("00" + s.substr(2,6)):s.substr(0,8);
        }else{
            return s.substr(0,2) == "12"?s.substr(0,8):std::to_string(stoi(s.substr(0,2))+12) + s.substr(2,6);
        }
    }