Home > database >  Convert string to date in kotlin
Convert string to date in kotlin

Time:12-14

could you help me?

I get a string of type 01092020, how could I convert to date type in 01/09 format, just month and year?

CodePudding user response:

You can substring your string and break into month and year e.g DDMMYYYY

val dateStr = "01092020"
val dd = dateStr.substring(0..1)
val mm = dateStr.substring(2..3)
val yyyy = dateStr.substring(4 until dateStr.length)

val DDYY = "$dd/$yyyy"
val mmYYYY = "$mm/$yyyy"

CodePudding user response:

You should use DateTimeFormatter as follows:

fun main(args: Array<String>) {
    val dateString = "01092020"

    val readingFormatter = DateTimeFormatter.ofPattern("ddMMyyyy")
    val date = LocalDate.parse(dateString, readingFormatter)

    val writingFormatter = DateTimeFormatter.ofPattern("MM/yy")
    val formattedDate = date.format(writingFormatter)
    print(formattedDate)
}
  • Related