9

I try to get hour from Date data type in Kotlin but get this error:

'getter for hours: Int' is deprecated. Deprecated in Java

And my code:

val date:Date = ...
val hour = date.hours

this is deprecated and getHours() not found ...

reza_khalafi
  • 6,230
  • 7
  • 56
  • 82
  • I think you are looking for `getHours()`. That's what [oficial documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/-date/index.html) says – Jalil May 21 '19 at 09:33
  • I suggest that it’s a near-duplicate of [Fastest way to get hour of java.util.date?](https://stackoverflow.com/questions/38200459/fastest-way-to-get-hour-of-java-util-date) You may search for more similar questions. – Ole V.V. May 21 '19 at 10:02
  • 1
    I recommend you don’t use `Date`. That entire class is poorly designed and long outdated. Instead use an appropriate class from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 21 '19 at 10:13
  • 1
    Possible duplicate of [Java: getMinutes and getHours](https://stackoverflow.com/questions/907170/java-getminutes-and-gethours) – Ole V.V. May 21 '19 at 10:20

1 Answers1

17

getHours() is deprecated. It replaced by Calendar.get(Calendar.HOUR_OF_DAY)

val date:Date = ... // your date
val cal = Calendar.getInstance()
cal.time = date
val hours = cal.get(Calendar.HOUR_OF_DAY)
Nikunj Paradva
  • 15,332
  • 5
  • 54
  • 65