kotlinx-datetime
kotlinx-datetime copied to clipboard
How to convert string in format "yyyy-mm-dd hh:mm:ss" to localDateTime?
I am getting a date in a format like this "2021-03-26 22:02:53" from the API which is not ISO format, and I created a custom serializer for it but I am getting an error. I also do not want to use ISO format, and I want to send back the date as "yyyy-mm-dd hh:mm:ss".
Since We can not use Java.Date in Kotlin multiplatform, what is the proper solution to serialize date format like this?
Thanks
Sorry, we don't have such functionality currently. There are many requests for it though (https://github.com/Kotlin/kotlinx-datetime/labels/formatters), so we are thinking about this.
The format looks very similar to the ISO format of LocalDateTime, except that the date and time components are separated with a space instead of T. So as a workaround, you can replace ' ' with 'T' and use LocalDateTime.parse to parse the result:
LocalDateTime.parse("2021-03-26 22:02:53".replaceFirst(' ', 'T')
Can this issue be solved by giving an optional format string parameter to LocalDateTime.parse and using this format parameter in type DateTimeFormatter. ofPattern?
You can actually use the date time formatter to parse the string then use the local date to parse into your requirements
val formatter =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val formattedDate = LocalDate.parse(date, formatter)
Except that's Java. This library doesn't have DateTimeFormatter.