3

I am trying to add one month to a date with Calendar.getInstance() but I can't figure out why there is error "java.lang.ClassCastException : java.util.Date cannot be cast to java.lang.Number" when trying to get the Calendar to a Date object.

Here's the source code that I am using :

    val date = Date()
    val cal = Calendar.getInstance()
    cal.time = date
    cal.add(Calendar.MONTH, 1)
    val datePlusOneMonth: Date = cal.time
KotlinIsland
  • 799
  • 1
  • 6
  • 25

2 Answers2

10

Thank you Sergey... The code runs ok. But I have been disappointed because I added a useless line of code in order to debug and I had put a breakpoint on it :

val datePlusOneMonth: Date = cal.time
val ok = false

And I had put the breakpoint on the "val ok = false" and the debugger never stopped on "val ok = false" because "ok" was never used.

Then to have the debugger stop on "val ok = false" I had to do the following :

val datePlusOneMonth: Date = cal.time
val ok = false
val ok2 = ok

And then I could add the breakpoing on "val ok = false" and yes the code runs well.

KotlinIsland
  • 799
  • 1
  • 6
  • 25
2

try this code

val datePlusOneMonth = Calendar.getInstance().run {
    add(Calendar.MONTH, 1)
    time
}
ib_ganz
  • 111
  • 1
  • 8