Time Conversion

Sort by

recency

|

868 Discussions

|

  • + 0 comments

    python

    def timeConversion(s):

    len_s = len(s)      
    if len_s !=10:
        return None
    am_or_pm = str(s)[len_s-2]
    time_24 = str(s)[:-2]
    hour = int(str(s)[:2])
    
    if am_or_pm == 'P' and  hour!=12:
        time_24 = str(hour + 12 )+str(s)[2:-2]
    else:
        if am_or_pm == 'A' and hour ==12:
            time_24 = "00"+str(s)[2:-2]
    
    return time_24
    
  • + 0 comments

    my solution in C#:

    public static string timeConversion(string s)
        {
            string hour = s.Substring(0,2);
            string amPm = s.Substring(s.Length - 2, 2);
            if (hour.Equals("12")) {
                if (amPm.Equals("AM")) {
                    return "00" + s.Substring(2, s.Length - 4);
                }
                else {
                    return s.Substring(0, s.Length - 2);
                }
            }
            else {
                if (amPm.Equals("AM")) {
                    return s.Substring(0, s.Length - 2);
                }
                else {
                    return (int.Parse(hour) + 12).ToString() + s.Substring(2, s.Length - 4);
                }
            }
        }
    
  • + 0 comments

    My solution in javascript :

    function timeConversion(s) {
        // Write your code here
        const ampm = s.slice(-2)
        const h = s.slice(0,2)
        const rest = s.slice(2,-2)
        // console.log(n) // 12
        // console.log(t) // "PM"
        if ( ampm === "PM" ) {
         return h === "12" ? `12${rest}` : `${String(Number(h) + 12)}${rest}`
        } else {
          return h === "12" ? `00${rest}` : `${h}${rest}`
        }
    }
    
  • + 0 comments

    My solution in Java:

        public static String timeConversion(String s) {
            int hour = Integer.parseInt(s.substring(0, 2));
            
            if (s.endsWith("PM")) {
                if (hour != 12) {
                   hour = hour + 12; 
                }
     
                s = Integer.toString(hour) + s.substring(2, s.length() - 2);
            } else {
                if (hour == 12) {
                    hour = 0;
                }
                s = String.format("%02d", hour) + s.substring(2, s.length() - 2);
            }
        
            
            return s;
        }
    
  • + 0 comments

    My solution with Python:

    def timeConversion(s):
        
        h = int(s[0:2])
        
        if s[-2:]=='PM':
            h+=12
            
        if s[0:2] == '12':
            h-=12
        
        converted = str(h).zfill(2) + s[2:-2]
        
        return converted