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

4

34

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);
Yip answered 20/1, 2009 at 6:47 Comment(1)
This troublesome class Calendar is now outmoded, supplanted by the modern java.time classes built into Java 8 and later.Basuto
T
80

From here:

calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
Trilobate answered 20/1, 2009 at 6:58 Comment(0)
S
5

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

Spatula answered 20/1, 2009 at 6:55 Comment(0)
P
2

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

Possible answered 13/1, 2018 at 16:9 Comment(4)
"In 2018 no one should use the Calendar class anymore" - have you heard about Android ;)Scherzo
Yes, I have an Android device, @KonradMorawski. I have also heard about ThreeTenABP, the backport of java.time to earlier Android versions. More in this question: How to use ThreeTenABP in Android Project.Possible
Sadly, modern Java datetime API isn't available on Android out of the box as of now. The backport is a third party library, and as such it's arguably an overkill for apps that don't do that much of datetime-related computations. One thing for sure, the legacy API is plain ridiculous.Scherzo
There’s room for improvement. The ThreeTen Backport was developed by the original developers of java.time, though the Android adaptation is probably made by a third party. java.time comes out of the box from API level 26 (that’s fairly new, I believe).Possible
J
0

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

calendar.set(Calendar.SECOND, 0);

Janae answered 3/1, 2021 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.