How to set time to 24 hour format in Calendar

AndroidDev picture AndroidDev · Feb 20, 2013 · Viewed 117.7k times · Source

I need to set the time on the current date. The time string is always in 24 hour format but the result I get is wrong:

  SimpleDateFormat df = new SimpleDateFormat("kk:mm");
  Date d1 = df.parse("10:30");
  Calendar c1 = Calendar.getInstance();
  c1.set(Calendar.HOUR, d1.getHours());
  c1.set(Calendar.MINUTE, d1.getMinutes());

The date should be today's date and the time set to 10:30. Instead the time in c1 ends up being 22:30. How can I force the calendar control to recognize my time is 24 hour format?

EDIT: If I just do this:

Calendar c1 = Calendar.getInstance();
c1.set(Calendar.HOUR, 10);
c1.set(Calendar.MINUTE, 30);

This gives me the same result. Why?

Answer

AndroidDev picture AndroidDev · Feb 20, 2013

Replace this:

c1.set(Calendar.HOUR, d1.getHours());

with this:

c1.set(Calendar.HOUR_OF_DAY, d1.getHours());

Calendar.HOUR is strictly for 12 hours.