Conversion from 12 hours time to 24 hours time in java
java.time
In Java 8 and later it could be done in one line using class java.time.LocalTime.
In the formatting pattern, lowercase hh
means 12-hour clock while uppercase HH
means 24-hour clock.
Code example:
String result = // Text representing the value of our date-time object.
LocalTime.parse( // Class representing a time-of-day value without a date and without a time zone.
"03:30 PM" , // Your `String` input text.
DateTimeFormatter.ofPattern( // Define a formatting pattern to match your input text.
"hh:mm a" ,
Locale.US // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
) // Returns a `DateTimeFormatter` object.
) // Return a `LocalTime` object.
.format( DateTimeFormatter.ofPattern("HH:mm") ) // Generate text in a specific format. Returns a `String` object.
;
See this code run live at IdeOne.com.
15:30
See Oracle Tutorial.
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