Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin DateTimeformat returning wrong month [duplicate]

Simple code, but something is wrong! I'm new to Kotlin, trying to take a date string and convert it into Date() format. When I convert back it gives wrong month. Example:

var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("America/New_York")
cal.set(2018, 1, 20)
val date: Date = cal.time
println(date)  //This prints: Tue Feb 20 23:25:59 EST 2018

Why am I getting Feb when month is set to 1 (January)?

Ultimately, I want to take a string in the format of "MM/dd/yyyy" and convert that to Date() format, but seem to be having trouble (need to support API 15), and using Calendar is my attempt to do this without the date formatters that need later APIs. Any ideas on a better way?

like image 303
FlatDog Avatar asked Feb 15 '26 03:02

FlatDog


1 Answers

Months for the Calendar class in Java are 0-indexed.

cal.set(2018, 0, 20)

is what you what.

However, this is why it's generally better to use the final int fields defined in the Calendar class, , rather than hardcoding the number. In this case, that's JANUARY. See here.

So that would give:

cal.set(2018, Calendar.JANUARY, 20)

like image 135
ubadub Avatar answered Feb 16 '26 18:02

ubadub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!