Pablo Fernandez
Pablo Fernandez

Reputation: 287390

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

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);

Upvotes: 34

Views: 65845

Answers (4)

maqsats
maqsats

Reputation: 358

In addition to the great accepted answer by Xn0vv3r, don't forget to set

calendar.set(Calendar.SECOND, 0);

Upvotes: 0

Anonymous
Anonymous

Reputation: 86203

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

Upvotes: 2

Rahul
Rahul

Reputation: 13056

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

Upvotes: 5

Xn0vv3r
Xn0vv3r

Reputation: 18184

From here:

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

Upvotes: 80

Related Questions