Question

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);
Was it helpful?

Solution

From here:

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

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top