Time Conversion

Sort by

recency

|

337 Discussions

|

  • + 0 comments

    I think one approrach to use Javascript string split.

        const [time, period] = time12h.split(/(AM|PM)/);
        const [hours, minutes, seconds] = time.split(':');
        const hours24h = period === 'PM' && hours !== '12' ? parseInt(hours) + 12 : hours === '12' && period === 'AM' ? '00' : hours;
        return `${hours24h}:${minutes}:${seconds}`;
    
  • + 0 comments

    Java

        public static String timeConversion(String s) {
            if (s.charAt(8) == 'P') {
                if (Integer.valueOf(s.substring(0, 2)) < 12) {
                  String res = String.valueOf(Integer.valueOf(s.substring(0, 2)) + 12);
                    res = res.concat(s.substring(2, 8));
                    return res;
                } else return s.substring(0, 8);            
            } else {
                if (Integer.valueOf(s.substring(0, 2)) < 12) {
                    return s.substring(0, 8);
                } else {
                    String res = "00";
                    res = res.concat(s.substring(2, 8));
                    return res;
                }  
            }
        }
    
  • + 0 comments

    C# Code

    public static string timeConversion(string s) { var time = DateTime.Parse(s); return time.ToString("HH:mm:ss"); }

  • + 0 comments

    I tried the most manual approach to do these. I am not sure if these the best way to do it . PLease someone try and lets discuss if these is an acceptable answer for interviewer or not . string timeConversion(string s) { vector result; stringstream ss(s); string strToken;

    while(getline(ss,strToken,':')){
        result.push_back(strToken);
    }
    
    if(result[2][2] == 'A'){
        if(result[0] == "12"){
            result[0] = "00";
        }
    }
    else{
        int value = stoi(result[0]);
        if(value >= 1 && value <= 11){
            result[0] = to_string(12 + value);
        }
    }
    
    string ans = result[0] + ":" + result[1] + ":" + result[2].erase(4-2);
    return ans;  
    

    }

  • + 0 comments
    public static String timeConversion(String s) {
    // Write your code here
    
    return LocalTime.parse(s, DateTimeFormatter.ofPattern("hh:mm:ssa", Locale.US))
    .format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    
    
    
    }