How do you set the time and only the time in a calendar in Java?

58,881

Solution 1

From here:

calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);

Solution 2

Use set(int field, int value). The first parameter is the field number for HOUR/MINUTE/SECOND.

Solution 3

In 2018 no one should use the Calendar class anymore. It it long outmoded, and java.time the modern Java date and time API is so much nicer to work with. Instead use, depending on you exact requirements, a ZonedDateTime or perhaps an OffsetDateTime or LocalDateTime. In either case, set the time of day this way:

dateTime = dateTime.with(LocalTime.of(hour, minute));

Link: Oracle Tutorial Date Time

Share:
58,881
pupeno
Author by

pupeno

You can find my blog at https://pupeno.com where I publish about coding and other stuff.

Updated on January 04, 2021

Comments

  • pupeno
    pupeno over 3 years

    Having the hours and minutes, is there any easier or better way to set it into a Calendar object than:

    calendar.set(calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH),
                            calendar.get(Calendar.DAY_OF_MONTH),
                            hour, minute);