0

i get the hour and minutes out of a TimePickerDialog:

public void onTimeSet(TimePicker view, int hour, int minute) {
    // Do something with the time chosen by the user
}

I want to display this time somewhere else. My approach would be to check the user settings for 12h or 24h format with

DateFormat.is24HourFormat()

and then build the time text manually.

My question: Is there a better way to do that?

Florian Walther
  • 6,237
  • 5
  • 46
  • 104

2 Answers2

2

You can use SimpleDateFormat like this for 24 hours:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss);

or change HH to hh to get 12 hours format:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss);

then just use:

dateFormat.format(yourDate);

which you can get using calendar:

SimpleDateFormat dateFormat;
if (DateFormat.is24HourFormat()) {
    dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss);
} else {
    dateFormat = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss);
}
Calendar c = new Calendar.getInstance();
c.set(Calendar.HOUR, yourIntHour); // Or HOUR_OF_DAY
c.set(Calendar.MINUTE, yourIntMinute);
Date d = c.getTime();
String dateResult = dateFormat.format(d);

You can use HOUR_OF_DAY instead of HOUR: (soruce: javadoc)

public static final int HOUR

Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.

public static final int HOUR_OF_DAY

Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.

antoninkriz
  • 966
  • 4
  • 18
  • 36
  • Thank you, but i always have to make that manual check for DateFormat.is24HourFormat() ? So there is no way to save the result of the timePicker in a way that it displays the correct format automatically when i use it? – Florian Walther Aug 25 '17 at 22:06
  • This may be an answer for you: https://stackoverflow.com/questions/11093182/date-formatting-based-on-user-locale-on-android I personally like the most the last answer – antoninkriz Aug 25 '17 at 22:10
0

You can force the timepicker to be 12 hours picker using timePicker.setIs24HourView(boolean):

timePicker.setIs24HourView(DateFormat.is24HourFormat(getContext()));
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
  • I mean that you have not to handle the time text manually. Change to format of timepicker and get the desired format of time. – Ali Sheikhpour Aug 25 '17 at 21:57
  • Thank you for your answer. But this way i force the 12 format upon every user, right? Since i am from germany myself i want to give the possibilty to user 24 hour format. – Florian Walther Aug 25 '17 at 22:12