33

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);
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622
  • 1
    This troublesome class `Calendar` is now outmoded, supplanted by the modern java.time classes built into Java 8 and later. – Basil Bourque Jan 13 '18 at 16:31

4 Answers4

79

From here:

calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
user846316
  • 6,037
  • 6
  • 31
  • 40
Xn0vv3r
  • 17,766
  • 13
  • 58
  • 65
5

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Rahul
  • 12,886
  • 13
  • 57
  • 62
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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    *"In 2018 no one should use the `Calendar` class anymore"* - have you heard about Android ;) – Konrad Morawski Aug 17 '18 at 17:02
  • Yes, I have an Android device, @KonradMorawski. I have also heard about [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP/blob/master/build.gradle), the backport of java.time to earlier Android versions. More in [this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Aug 17 '18 at 17:06
  • 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. – Konrad Morawski Aug 17 '18 at 17:56
  • 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). – Ole V.V. Aug 17 '18 at 18:04
0

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

calendar.set(Calendar.SECOND, 0);

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
prsnlme
  • 179
  • 8