Time Conversion

Sort by

recency

|

5084 Discussions

|

  • + 0 comments

    Typescript:

    let hours = s.split(':')[0].toString();
    let minutes = s.split(':')[1].toString();
    let seconds = (s.split(':')[2].slice(0, 2)).toString();
    let timeType = s.split(':')[2].slice(-2);
    
    if (timeType == 'AM' && hours == '12') {
       hours = '00';
    } else if (timeType == 'PM' && Number(hours) < 12) {
       hours = (Number(hours) + 12).toString();
    }
    
    return `${hours}:${minutes}:${seconds}`;
    
  • + 0 comments

    C# Code

    public static string timeConversion(string s)
        {
            try
            {
                // Parse the input time into a DateTime object
                DateTime parsedTime = DateTime.ParseExact(s, "hh:mm:sstt", CultureInfo.InvariantCulture);
    
                // Convert to military (24-hour) time format
                return parsedTime.ToString("HH:mm:ss");
            }
            catch (FormatException)
            {
                throw new ArgumentException("Invalid time format. Please use hh:mm:ssAM or hh:mm:ssPM.");
            }
        }
    
  • + 0 comments

    Java

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

    Python

    def timeConversion(s):
        hour = s[0:2]
        am_pm = s[8:10]
    
        if hour == "12":
            if am_pm == "AM":
                hour = "00"
        elif am_pm == "PM":
            hour = str(int(hour)+12)
        return f"{hour}{s[2:8]}"
        
    
  • + 0 comments

    Theres a simple way to do this with datetime which will save alot of time, but it doesnt hurt to do it the hard way and then take a look at the quick way:

    datetime.strptime(s, "%I:%M:%S%p").strftime("%H:%M:%S")