38

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?

Johann
  • 27,536
  • 39
  • 165
  • 279
  • http://stackoverflow.com/questions/7435005/convert-a-string-of-time-to-24-hour-format – Ingo Feb 20 '13 at 13:25
  • setTime takes a Date. The date will end up overwriting the calendar's date. – Johann Feb 20 '13 at 13:26
  • My time is ALWAYS in 24 hour format. That posting clearly indicates am/pm format. – Johann Feb 20 '13 at 13:32
  • 1
    `getHours()` and `getMinutes()` methods are deprecated. And it looks like you don't need to use them. What happens if you just pass 10 and 30 to `Calendar` setters? – Bhesh Gurung Feb 20 '13 at 13:32
  • I just tried that and that gives me the same result. Clearly something stupid going on with the Calendar object. – Johann Feb 20 '13 at 13:35

9 Answers9

196

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.

Johann
  • 27,536
  • 39
  • 165
  • 279
  • +1 Javadoc says it very clear "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." – Lluis Martinez Jul 28 '17 at 12:19
  • I have been trying to solve an issue the whole day and you saved me! Thank you so much! – huss_a Jul 02 '22 at 19:22
11

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);
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Aliaksei Bulhak
  • 6,078
  • 8
  • 45
  • 75
6

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

Sam Strawbridge
  • 106
  • 1
  • 3
4

if you replace in the function SimpleDateFormat("hh") with ("HH") will format the hour in 24 hours instead of 12.

SimpleDateFormat df = new SimpleDateFormat("HH:mm");
2

I am using fullcalendar on my project recently, I don't know what exact view effect you want to achieve, in my project I want to change the event time view from 12h format from

enter image description here

to 24h format.

enter image description here

If this is the effect you want to achieve, the solution below might help:

set timeFormat: 'H:mm'

Lying_cat
  • 1,288
  • 2
  • 12
  • 16
1

Here you will get all kinds of time related problems. I hope this will solve your problem.

public class MyClass {

    public static void main(String[] args) {


        Calendar cal = Calendar.getInstance();

        // To get the current hour
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        System.out.println("hour: " + hour);

        // To get the current time in 12 hours format
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US);
        String a = sdf.format(cal.getTime());
        System.out.println("Time: " + a);

        // To get the desired time in 12 hours format from 23 hours format
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a",Locale.ENGLISH);
        String a1 = sdf1.format(cal.getTime());
        System.out.println("Time: " + a1);

        /*  H Hour in day (0-23) 
            k Hour in day (1-24) 
        */

        //To get the desired time in 24 hours format as 0-23 or 1-24
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
        SimpleDateFormat sdf3 = new SimpleDateFormat("kk:mm",Locale.ENGLISH);
        String a2 = sdf2.format(cal.getTime());
        String a3 = sdf3.format(cal.getTime());
        System.out.println("Time: " + a2);
        System.out.println("Time: " + a3);

        //For example, time like 12:30 PM. How can i convert to 24 hours time in java?

        SimpleDateFormat bigFormat = new SimpleDateFormat("kk:mm");
        SimpleDateFormat smallFormat = new SimpleDateFormat("hh:mm a");

        Date date = null;
        try {
            date = smallFormat.parse("12:30 AM");
        } catch (ParseException e) {
            e.printStackTrace();
        }        
        System.out.println(smallFormat.format(date) + " = " + bigFormat.format(date));

    }

}
MrLeeh
  • 5,321
  • 6
  • 33
  • 51
1

private void setClock() {

    Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {
        Calendar cal = Calendar.getInstance();
        int second = cal.get(Calendar.SECOND);
        int minute = cal.get(Calendar.MINUTE);
        int  hour = cal.get(Calendar.HOUR_OF_DAY);
        eski_minut = minute;
        if(second < 10){

            time_label.setText(hour + ":" + (minute) + ":0" + second);

        }else if (minute < 10){
            time_label.setText(hour + ":0" + (minute) + ":0" + second);

        }
        else {
        time_label.setText(hour + ":" + (minute) + ":" + second);}
    }),
            new KeyFrame(Duration.seconds(1))
    );
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Roel Koops Nov 29 '17 at 12:07
0

Try this :

SimpleDateFormat df = new SimpleDateFormat("hh:mm");

Or

SimpleDateFormat df = new SimpleDateFormat("KK:mm");

Reference : SimpleDateFormat

Iswanto San
  • 18,263
  • 13
  • 58
  • 79
  • Neither of those work. Same result: 22:30. They need to rename SimpleDateFormat to ComplexAndStupidDateFormat. – Johann Feb 20 '13 at 13:30
0

tl;dr

LocalTime.parse( "10:30" )  // Parsed as 24-hour time.

java.time

Avoid the troublesome old date-time classes such as Date and Calendar that are now supplanted by the java.time classes.

LocalTime

The java.time classes provide a way to represent the time-of-day without a date and without a time zone: LocalTime

LocalTime lt = LocalTime.of( 10 , 30 );  // 10:30 AM.
LocalTime lt = LocalTime.of( 22 , 30 );  // 22:30 is 10:30 PM.

ISO 8601

The java.time classes use standard ISO 8601 formats by default when generating and parsing strings. These formats use 24-hour time.

String output = lt.toString();

LocalTime.of( 10 , 30 ).toString() : 10:30

LocalTime.of( 22 , 30 ).toString() : 22:30

So parsing 10:30 will be interpreted as 10:30 AM.

LocalTime lt = LocalTime.parse( "10:30" );  // 10:30 AM.

DateTimeFormatter

If you need to generate or parse strings in 12-hour click format with AM/PM, use the DateTimeFormatter class. Tip: make a habit of specifying a Locale.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154