Search code examples
javadatetimesyntaxdatetime-conversion

Time Conversion from 12-hour to 24-hour clock in Java


I have a time in a string in the following format.

"MM/dd/yyyy hh:mm AM/PM"

I need to get the time in 24:00 hours format

ex:

String str = "04/30/2013 10:20PM"

I need to get the time as 22:20


Solution

  • You have to use SimpleDateFormat to any kind of date-time conversion.
    You can try this:

    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class DateConversion {
       public void convertDate() {
          try{
           SimpleDateFormat df = new SimpleDateFormat("HH:mm");
           SimpleDateFormat pf = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
           Date date = pf.parse("10:20PM");
           System.out.println(pf.format(date) + " = " + df.format(date));
            }catch(Exception e){
            // Do your exception handling over here.
            }
       }
    }
    

    This will solve your problem I guess.
    This will give an output : 22:20

    Please let me know in case of any issue.