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?
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.
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.
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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With