Skip to content
Advertisement

Conversion from 12 hours time to 24 hours time in java

In my app, I have a requirement to format 12 hours time to 24 hours time. What is the method I have to use?

For example, time like 10:30 AM. How can I convert to 24 hours time in java?

Advertisement

Answer

Try this:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
   public static void main(String [] args) throws Exception {
       SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
       SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
       Date date = parseFormat.parse("10:30 PM");
       System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
   }
}

which produces:

10:30 PM = 22:30

See: http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement