In case you decide not to use outdated libraries, you may want to take a look at java.time
. There's a kotlinx.datetime
currently under development, but it is based on java.time
anyway.
You could parse your String
like this:
import java.time.format.DateTimeFormatter
import java.time.ZonedDateTime
import java.util.Locale
fun main() {
// your example
val input = "Thu, 09 Jun 2022 19:20:00 GMT"
// define a formatter that parses Strings like yours
val dtf = DateTimeFormatter.ofPattern("EEE, dd MMM uuuu HH:mm:ss O",
Locale.ENGLISH)
// parse the String and get a ZonedDateTime
val zdt = ZonedDateTime.parse(input, dtf)
// print the result using the ISO format
println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME))
// or print it using the formatter that parsed your example
println(zdt.format(dtf))
}
This code outputs two lines:
2022-06-09T19:20:00Z
Thu, 09 Jun 2022 19:20:00 GMT
I suggest you make your fun
return a java.time.ZonedDateTime
…
For completeness…
You can get rid of defining your own formatter in this case, there's a prebuilt one for the RFC1123 format for date plus time. The following code does the same as the one above but uses the built-in DateTimeFormatter.RFC_1123_DATE_TIME
:
fun main() {
// your example
val input = "Thu, 09 Jun 2022 19:20:00 GMT"
// choose a prebuilt formatter that parses RFC-formatted Strings
val rfc1123dtf = DateTimeFormatter.RFC_1123_DATE_TIME
// parse the String using the formatter and get a ZonedDateTime
val zdt = ZonedDateTime.parse(input, rfc1123dtf)
// print the result using the ISO format
println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME))
// or print it using the formatter that parsed your example
println(zdt.format(rfc1123dtf))
}