kotlinx-datetime icon indicating copy to clipboard operation
kotlinx-datetime copied to clipboard

How to convert string in format "yyyy-mm-dd hh:mm:ss" to localDateTime?

Open ccc-sseylani opened this issue 4 years ago • 3 comments

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?

image image

Thanks

ccc-sseylani avatar Jun 07 '21 17:06 ccc-sseylani

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.

dkhalanskyjb avatar Jun 16 '21 10:06 dkhalanskyjb

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')

ilya-g avatar Dec 16 '21 17:12 ilya-g

Can this issue be solved by giving an optional format string parameter to LocalDateTime.parse and using this format parameter in type DateTimeFormatter. ofPattern?

galipkaya avatar Jan 24 '22 13:01 galipkaya

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)

DenisGithuku avatar Nov 07 '22 15:11 DenisGithuku

Except that's Java. This library doesn't have DateTimeFormatter.

dkhalanskyjb avatar Nov 07 '22 15:11 dkhalanskyjb