When I am selecting time 06.30 Am or 06.30 (24 hour format), I get out put as 18.30. And when I am selecting time 18.00 or 06.00PM , I getting 06.00 as output.
My code is this…
private void handleTimeButton() {
final Calendar calendar = Calendar.getInstance();
int HOUR = calendar.get(Calendar.HOUR);
int MINUTE = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR, hour);
calendar1.set(Calendar.MINUTE, minute);
String text = (String) DateFormat.format("HH:mm", calendar1);
etTime.setText(text); //this is my output
}
}, HOUR, MINUTE, true); // tried both true and false
timePickerDialog.show();
}
I want my output to be in 24 hours format.
2
Answers
You can do either this,
or
You can refer here for your AM PM confusions
24-hour format to 12-hour format
12 hour format timepicker android
How to set Time with the help of Timepicker? with 12 hour format
java.time
The
java.util
Date-Time API and their formatting API,SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.Also, quoted below is a notice from the home page of Joda-Time:
Solution using
java.time
, the modern Date-Time API: Create aLocalTime
withhour
andminute
, and get the value ofLocalTime#toString
to be set toetTime
.Demo:
Output:
ONLINE DEMO
The modern Date-Time API is based on ISO 8601 and thus the
LocalTime#toString
returns the string in ISO 8601 format (which is also your desired format).Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness:
Just for the sake of completeness, given below is the solution using the legacy API:
Output:
ONLINE DEMO
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.