How to convert Calendar to Date in Kotlin?
Solution 1
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.
Solution 2
try this code
val datePlusOneMonth = Calendar.getInstance().run {
add(Calendar.MONTH, 1)
time
}
Related videos on Youtube
KotlinIsland
I have been involved in many projects for many companies such as Renault, Orange, SFR, Poclain Hydraulics, Bouygues Telecom... I have been involved in a Car-to-Car European Research Project called GST (Global Systems For Telematics).
Updated on May 25, 2022Comments
-
KotlinIsland almost 2 years
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
-
Sergio about 5 yearsThe code you provided works fine on my side. Maybe error appears somewhere else in your code? Please check logs and look for the line number of the error
-
Amine about 5 yearscal.time = date has not need here, otherwise what line gives you this error ?
-
KotlinIsland about 5 yearsThe error happens on val datePlusOneMonth: Date = cal.time
-
KotlinIsland about 5 yearsSergey, are you sure that it runs ok ? Because the exception does not trigger any bug in the application. It is only when I put a breakpoint and then go to Evaluate Expression window that I see the error when calling cal.time
-
KotlinIsland about 5 yearsAmine, you say right, cal.time = Date is not needed. Thanks. (Error still happening anyway)
-
Sergio about 5 yearsYes, the code runs fine on my side
-
KotlinIsland about 5 yearsSo you have a value in datePlusOneMonth ?
-
KotlinIsland about 5 years
-
Sergio about 5 yearsYes I have. You can set log after line
val datePlusOneMonth: Date = cal.time
and check it -
KotlinIsland about 5 yearsOne thing I find bizarre is that when adding a try/catch block, then the code does not go in the catch block...
-
Sergio about 5 yearsBecause it is not throwing the exception)
-
-
KotlinIsland about 5 yearsOk thanks for the answer, but we figured out that my code runs correctly. Anyway I'll consider this next time.