you have problem because the format of the date is not supported, I invite you to read this article https://www.claudebueno.com/programmation/comment-gerer-la-date-et-lheure-avec-kotlin.htm but in your case if you want that the code runs, change the format of date, like this:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.LocalDate

fun main() {
    //example
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.BASIC_ISO_DATE
    val formatted = current.format(formatter)
    println("Current Date is: $formatted")
    
    //your code
    val dates = /*"20 Aug 2012"*/ "20120820"
    val datess = LocalDate.parse(dates, DateTimeFormatter.BASIC_ISO_DATE)
    println(datess)
}
Answer from zerbene on Stack Overflow
🌐
Kotlin
kotlinlang.org › api › kotlinx-datetime › kotlinx-datetime › kotlinx.datetime › -local-date
LocalDate | kotlinx-datetime – Kotlin Programming Language
parse and toString methods can be used to obtain a LocalDate from and convert it to a string in the ISO 8601 extended format. See sample 3. parse and LocalDate.format both support custom formats created with Format or defined in Formats.
Top answer
1 of 2
7

you have problem because the format of the date is not supported, I invite you to read this article https://www.claudebueno.com/programmation/comment-gerer-la-date-et-lheure-avec-kotlin.htm but in your case if you want that the code runs, change the format of date, like this:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.LocalDate

fun main() {
    //example
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.BASIC_ISO_DATE
    val formatted = current.format(formatter)
    println("Current Date is: $formatted")
    
    //your code
    val dates = /*"20 Aug 2012"*/ "20120820"
    val datess = LocalDate.parse(dates, DateTimeFormatter.BASIC_ISO_DATE)
    println(datess)
}
2 of 2
6

tl;dr ⇒ You are using the wrong pattern for parsing

  1. Your date String is of the format dd MMM uuuu (a non ISO format) but you are trying to parse it with a DateTimeFormatter.ISO_LOCAL_DATE

  2. Your datetime String is of the format MM/dd/uuuu hh:mm:ss a (non ISO) but you are trying to parse it with a DateTimeFormatter.ISO_LOCAL_DATE, which is at least doubly wrong because that formatter tries to parse an ISO date. Your String is non ISO and contains more information (time of day) than this formatter is able to parse.

There are several built-in DateTimeFormatters, like the one you are currently using, but you need to use a correct one or if there is none, create one that covers your String(s) yourself (either by DateTimeFormatter.ofPattern(...) or by using a DateTimeFormatterBuilder).

Here's a small example for your String examples:

fun main(args: Array<String>) {
    // your example Strings
    val dateFirst = "20 Aug 2012"
    val dateSecond = "12/16/2020 12:00:00 AM"
    // you need two different formatters here, your Strings differ in format and content
    val firstFormatter = DateTimeFormatter.ofPattern("dd MMM uuuu", Locale.ENGLISH)
    val secondFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm:ss a", Locale.ENGLISH)
    // then use those according to what you want to parse
    val localDate = LocalDate.parse(dateFirst, firstFormatter)
    val localDateTime = LocalDateTime.parse(dateSecond, secondFormatter)
    // use the built-in formatters for output
    println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE))
    println(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
}

Output (in ISO):

2012-08-20
2020-12-16T00:00:00
🌐
Kotlin
kotlinlang.org › api › kotlinx-datetime › kotlinx-datetime › kotlinx.datetime › -local-date-time › to-string.html
toString | kotlinx-datetime – Kotlin Programming Language
for the dual operation: obtaining LocalDateTime from a string. format · for formatting using a custom format. import kotlinx.datetime.* import kotlinx.datetime.format.* import kotlin.test.* fun main() { //sampleStart // Converting LocalDateTime values to strings check(LocalDate(2024, 2, 15).atTime(16, 48).toString() == "2024-02-15T16:48") check(LocalDate(2024, 2, 15).atTime(16, 48, 15).toString() == "2024-02-15T16:48:15") check(LocalDate(2024, 2, 15).atTime(16, 48, 15, 120_000_000).toString() == "2024-02-15T16:48:15.120") //sampleEnd } actual open override fun toString(): String(source)
🌐
Kotlin
kotlinlang.org › api › kotlinx-datetime › kotlinx-datetime › kotlinx.datetime › -local-date-time › -companion › parse.html
parse | kotlinx-datetime – Kotlin Programming Language
Parses a string that represents a datetime value including date and time components but without any time zone component and returns the parsed LocalDateTime value. If format is not specified, Formats.ISO is used.
🌐
Baeldung
baeldung.com › home › kotlin › kotlin strings › converting strings to date in kotlin
Converting Strings to Date in Kotlin | Baeldung on Kotlin
March 19, 2024 - fun givenString_whenCustomFormat_thenLocalDateTimeCreated() { val text = "2022-01-06 20:30:45" val pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val localDateTime = LocalDateTime.parse(text, pattern) Assertions.assertThat(localDateTime).isEqualTo("2022-01-06T20:30:45") } Sometimes, we need to work with the old API java.util.Date. Fortunately, since Kotlin has excellent compatibility with Java, we can use the SimpleDateFormat class. Let’s see now how to convert Strings into Date objects of type java.util.Date.
🌐
Baeldung
baeldung.com › home › kotlin › kotlin dates › working with dates in kotlin
Working with Dates in Kotlin | Baeldung on Kotlin
June 20, 2022 - Let’s suppose we have two dates, exactly 6 months apart from each other: var date1 = LocalDate.parse("2018-06-25") var date2 = LocalDate.parse("2018-12-25") Now, we can represent the distance between these two dates using Period’s between method: ... P stands for Period and 6M means 6 months. In this article, we have learned the basics of how to work with Dates in Kotlin.
🌐
Android Developers
developer.android.com › api reference › localdate
LocalDate | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Luasoftware
code.luasoftware.com › tutorials › kotlin › parse-date-string-to-localdate
Parse Date String to Localdate
val dateString = "2022-04-30"val date = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE).atStartOfDay()
Find elsewhere
🌐
Medium
raed-o-ghazal.medium.com › kotlinx-localdatetime-manipulation-for-kmm-eacfede93aba
Kotlinx.datetime manipulation KMP | by Raed Ghazal | Medium
September 10, 2024 - actual fun parse(str: String): LocalDateTime { val formatter = NSDateFormatter().apply { dateFormat = "dd/MM/yyyy - HH:mm" locale = NSLocale.currentLocale } return formatter .dateFromString(str) // extensions functions provided by kotlinx.datetime ?.toKotlinInstant() ?.toLocalDateTime(TimeZone.currentSystemDefault()) ?: throw IllegalStateException("Failed to convert String $str to LocalDateTime") } And that’s it, you are all good to go from here.
🌐
Kotlinlang
slack-chats.kotlinlang.org › t › 2236247 › given-a-localdate-how-do-i-format-it-as-a-localized-string-j
Given a `LocalDate` how do I format it as a localized string kotlinlang #kotlinx-datetime
Looks like it is very limited. https://github.com/Kotlin/kotlinx-datetime#converting-instant-and-local-datetime-to-and-from-string ... Thanks for the reply. I ended up with this stopgap: ... fun LocalDate.toJavaLocalDate(): java.time.LocalDate { return java.time.LocalDate.ofEpochDay(this.toEpochDays().toLong()) } someLocalDate.toJavaLocalDate().format(DateTimeFormatter.ofPattern("LLL dd"))
🌐
GitHub
github.com › Kotlin › kotlinx-datetime › issues › 128
How to convert string in format "yyyy-mm-dd hh:mm:ss" to localDateTime? · Issue #128 · Kotlin/kotlinx-datetime
June 7, 2021 - 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?
Author   ccc-sseylani
🌐
Intfast
code.intfast.ca › viewtopic.php
Kotlin: Convert date/time related types to String and back • Elegant Programming Club
{ if (valAsString == null) return null try { return LocalDate.parse(valAsString, dateFormatter) } catch (e: DateTimeParseException) { throw Exception("Cannot parse '$valAsString' to LocalDate.") } } fun toString (valAsLocalDate: LocalDate?): String? { if (valAsLocalDate == null) return null return dateFormatter.format(valAsLocalDate) } // LocalTime: fun toLocalTime (valAsString: String?): LocalTime?
🌐
GitHub
github.com › Kotlin › kotlinx-datetime
GitHub - Kotlin/kotlinx-datetime: KotlinX multiplatform date/time library · GitHub
Instant, LocalDateTime, LocalDate and LocalTime provide shortcuts for parsing and formatting them using the extended ISO 8601 format. The toString() function is used to convert the value to a string in that format, and the parse function in ...
Starred by 2.8K users
Forked by 131 users
Languages   Kotlin
🌐
GitHub
github.com › Kotlin › kotlinx-datetime › discussions › 253
Localized date-time formats · Kotlin/kotlinx-datetime · Discussion #253
What is not clear is: Imagine that kotlinx-datetime has with things like ES_ES_FORMAT = "d 'de' MMMM 'de' yyyy" built in for each locale. You'd write LocalDate.Format(Locale("es_es")) { year(); monthName(); dayOfMonth() }, and it would output ...
Author   Kotlin
🌐
GitHub
github.com › Kotlin › kotlinx-datetime › issues › 339
Consider removing `String.toLocalDate()`, `String.toInstant()`, etc. · Issue #339 · Kotlin/kotlinx-datetime
December 22, 2023 - Right now, we have two ways to parse something: LocalDate.parse("2024-01-23") "2024-01-23".toLocalDate() With the introduction of datetime formatting (#251), we'll get other ways to do exactly the same: LocalDate.Formats.ISO.parse("2024-...
Author   dkhalanskyjb
🌐
Kotlin
kotlinlang.org › api › kotlinx-datetime › kotlinx-datetime › kotlinx.datetime › format.html
format | kotlinx-datetime – Kotlin Programming Language
fun LocalDate.format(format: DateTimeFormat<LocalDate>): String(source) Formats this value using the given format. Equivalent to calling DateTimeFormat.format on format with this. import kotlinx.datetime.* import kotlinx.datetime.format.* import kotlin.random.* import kotlin.test.* fun main() { //sampleStart // Formatting a LocalDate value using predefined and custom formats check(LocalDate(2024, 4, 16).toString() == "2024-04-16") check(LocalDate(2024, 4, 16).format(LocalDate.Formats.ISO) == "2024-04-16") val customFormat = LocalDate.Format { monthName(MonthNames.ENGLISH_ABBREVIATED); char(' '); day(); chars(", "); year() } check(LocalDate(2024, 4, 16).format(customFormat) == "Apr 16, 2024") //sampleEnd }
🌐
Kotlin
kotlinlang.org › api › kotlinx-datetime › kotlinx-datetime › kotlinx.datetime › to-local-date-time.html
toLocalDateTime | kotlinx-datetime – Kotlin Programming Language
Note that while this conversion is unambiguous, the inverse (LocalDateTime.toInstant) is not necessarily so. ... import kotlinx.datetime.* import kotlinx.datetime.format.* import kotlin.test.* import kotlin.time.Instant import kotlin.time.Clock fun main() { //sampleStart // Converting an instant to a local date-time in a specific time zone val zone = TimeZone.of("America/New_York") val instant = Instant.parse("2023-06-02T12:30:00Z") val localDateTime = instant.toLocalDateTime(zone) check(localDateTime == LocalDate(2023, 6, 2).atTime(8, 30)) //sampleEnd }