Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set time to 24 hour format in Calendar

Tags:

java

calendar

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?

like image 625
Johann Avatar asked Feb 20 '13 13:02

Johann


People also ask

How do I convert a Date to 24-hour format?

The pattern dd/MM/yyyy hh:mm:ss aa is used for the 12 hour format and the pattern MM-dd-yyyy HH:mm:ss is used for the 24 hour format.

How do I make my Google calendar 24 hours?

If you want to use a 24 hour clock format in google Calendar then you can click the gear icon in Google Calendar on your computer and choose Settings. You can then select the Time format dropdown menu and click the 13:00 option.


3 Answers

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.

like image 136
Johann Avatar answered Sep 30 '22 23:09

Johann


use SimpleDateFormat df = new SimpleDateFormat("HH:mm"); instead

UPDATE

@Ingo is right. is's better use setTime(d1);

first method getHours() and getMinutes() is now deprecated

I test this code

SimpleDateFormat df = new SimpleDateFormat("hh:mm");
  Date d1 = df.parse("23:30");
  Calendar c1 = GregorianCalendar.getInstance();
  c1.setTime(d1);
  System.out.println(c1.getTime());

and output is ok Thu Jan 01 23:30:00 FET 1970

try this

SimpleDateFormat df = new SimpleDateFormat("KK:mm aa");
  Date d1 = df.parse("10:30 PM");
  Calendar c1 = GregorianCalendar.getInstance(Locale.US);
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");  
  c1.setTime(d1);
  String str = sdf.format(c1.getTime());
  System.out.println(str);
like image 42
Aleksei Bulgak Avatar answered Sep 30 '22 23:09

Aleksei Bulgak


You can set the calendar to use only AM or PM using

calendar.set(Calendar.AM_PM, int);

0 = AM

1 = PM

Hope this helps

like image 33
Sam Strawbridge Avatar answered Sep 30 '22 22:09

Sam Strawbridge