Time Conversion

Sort by

recency

|

331 Discussions

|

  • + 0 comments
    function timeConversion(s: string): string {
        if (s.startsWith("12") && s.endsWith("PM")) {
            return s.slice(0,8);
        } 
        return s.startsWith("12") ? `00${s.slice(2,8)}` : s.endsWith("AM") ? s.slice(0,8) : `${+s.slice(0,2) + 12}${s.slice(2,8)}`;
    }
    
  • + 0 comments

    Scala

    def timeConversion(s: String): String = {
        // Write your code here
            val isAM = if(s.toUpperCase().contains("AM")) true else false
                
        val timeArray = s.split(":")
        val hours = timeArray(0)
        val minutes = timeArray(1)
        val seconds = timeArray(2)
                
        val militaryTime: String = hours match {
            case "12" if(isAM) => s"00:${minutes}:${seconds}"
            case "12" => s"12:${minutes}:${seconds}"
            case s if(!isAM) => s"${(Integer.parseInt(hours) + 12)}:${minutes}:${seconds}"
            case _ =>  s
        }
        
        militaryTime.replace("PM","").replace("AM", "")
    
            
        }
    
  • + 0 comments

    It is unfortunate that HackerRank's supposedly C++20 environment is actually a C++17 environment. std::format would have been handy.

  • + 0 comments

    Pretty simple javascript solution. Just splitting the time into hours, mins and secs, checking if it's am or pm and adjusting the hours as needed, then rejoining

    function timeConversion(s) {
        // Write your code here
        let time = s.slice(0, 8).split(':')
        let ampm = s.slice(8)
        if(ampm === 'PM' && time[0] !== '12'){
            time[0] = parseInt(time[0]) + 12
        } else if(ampm === 'AM' && time[0] === '12'){
            time[0] = '00'
        }
        return time.join(':')
        
    
    }
    
  • + 0 comments

    Java:

    public static String timeConversion(String str) {

      String time12HourFormat = str;
    
        SimpleDateFormat inputFormat = new SimpleDateFormat("hh:mm:ssa");
    
        SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");
    
        try{
    
            Date date = inputFormat.parse(time12HourFormat);
    
            String time24HourFormat = outputFormat.format(date); 
    
            return time24HourFormat;
    
        } catch (ParseException e) {    
            e.printStackTrace();                    
        }
        return "";
       }