Search code examples
androidstringdatekotlinandroid-5.0-lollipop

Parse date from string on Android Lollipop


I have a date string like 2021-02-20 12:24:10 and I need to parse it to Date. I have the solution, which works on Nougat (API 24) and higher, but I need need the solution for Lollipop (API 21). The solution for Nougat is below

val parser = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val entryDate: Date = parser.parse(ticketResponse.entryDate)

I tried to use DateFormat, but I get ParseException when I try to parse my date

val entryDate: Date = DateFormat.getInstance().parse(ticketResponse.entryDate)

I understand it happens because my input string is not a standard representation of date, but I cannot easy change it, I get this date from server. I also didn't find way to set pattern for input date like for SimpleDateFormat.

I am surprised that where is no answer here in some old questions, all answers recommend to use SimpleDateFormat. Of course I can split date with dividers, but I would like to use not so bold approach.


Solution

  • if you haven't noticed there are two SimpleDateFormat classes with a different package: java.text.SimpleDateFormat; and android.icu.text.SimpleDateFormat; please try to use the first one it is added in api level 1 chek this link : https://www.datetimeformatter.com/how-to-format-date-time-in-kotlin/