We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Time Conversion
  2. Discussions

Time Conversion

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 277 Discussions, By:

votes

Please Login in order to post a comment

  • nkstatedev
    11 months ago+ 0 comments

    Python

    def timeConversion(s):
        h = int(s[:2])
        msec = s[2:8]
        h = h % 12 if s[-2:] == 'AM' else h % 12 + 12
        return f"{h:02}{msec}"
    
    105|
    Permalink
  • harrison6
    11 months ago+ 0 comments

    I don't know if this is in the spirit of these types of programming challenges, but I'm going to insist that this is the correct industry solution (c#):

        public static string timeConversion(string s)
        {
            var date = DateTime.Parse(s);
            return date.ToString("HH:mm:ss");
        }
    
    84|
    Permalink
  • ofurhieraphael20
    10 months ago+ 0 comments

    c++ code

    string timeConversion(string s) {
     int pos = s.find(":");
     int t = stoi(s.substr(0,pos));
     string r = s.substr(8,2);
    if(t == 12 && r =="AM")return "00"+s.substr(pos,6);
    else if(t <12 && r=="PM")return to_string((t+12))+s.substr(pos,6);
    else return s.substr(0,8);
    }
    
    17|
    Permalink
  • sumedhassk
    9 months ago+ 0 comments

    A simpler way with Java;

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    
    class Result {
    
        private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm:ssa");
        private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm:ss");
    
        public static String timeConversion(String s) {
            try {
                return TWENTY_FOUR_TF.format(
                        TWELVE_TF.parse(s));
            } catch (ParseException e) {
                return s;
            }
        }
    
    }
    
    14|
    Permalink
  • sundaynwoye23
    7 months ago+ 0 comments

    JavaScript

    function timeConversion(s) {
        // Write your code here
        let hours = s.substr(0, 2);
        let minutes = s.substr(3, 2);
        let seconds = s.substr(-4, 2);
        let modifier = s.substr(-2, 2);
        if (hours === '12') {
            hours = '00';
        }
        if (modifier === 'PM') {
            hours = parseInt(hours, 10) + 12;
        }
        let time = `${hours}:${minutes}:${seconds}`;
        return time;
    
    }
    
    13|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature