Reputation: 287390
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
Reputation: 358
In addition to the great accepted answer by Xn0vv3r, don't forget to set
calendar.set(Calendar.SECOND, 0);
Upvotes: 0
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
Reputation: 13056
Use set(int field, int value). The first parameter is the field number for HOUR/MINUTE/SECOND.
Upvotes: 5