Home > Blockchain >  Kotlin: how to get the date from a MM/yy formatted input?
Kotlin: how to get the date from a MM/yy formatted input?

Time:12-07

How do I parse strings of the MM/yy format (ex: 12/22) to kotlin date objects ? Can a date object even exist without a day value ? I've tried the following :

import java.time.LocalDate
import java.util.Locale
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder


fun main() {
    var str_date = "06/22"
    
    val df: DateTimeFormatter = DateTimeFormatterBuilder()
    .appendPattern("MM/yy")
    .toFormatter(Locale.ENGLISH);
    
    println(LocalDate.parse(str_date, df))
}

which results in the following exception:

java.time.format.DateTimeParseException: Text '06/22' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2022, MonthOfYear=6},ISO of type java.time.format.Parsed

CodePudding user response:

A Java LocalDate requires a day, month, and year, so it can't parse 06/22.

If you need to parse only a month and year, then there's YearMonth

import java.time.YearMonth
import java.time.format.DateTimeFormatterBuilder
import java.util.Locale

fun main() {
  val monthYearFormatter = DateTimeFormatterBuilder()
    .appendPattern("MM/yy")
    .toFormatter(Locale.ENGLISH)

  // prints 2022-06
  println(YearMonth.parse("06/22", monthYearFormatter))

  // error: Invalid value for MonthOfYear (valid values 1 - 12): 13
  println(YearMonth.parse("13/22", monthYearFormatter))
}

CodePudding user response:

use DateTimeFormatter and LocalDate can do this job:

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

fun t2() {
    val dateFormat = "MM/yy"
    val formatter = DateTimeFormatter.ofPattern(dateFormat)

    val input = "12/22"
    val date = LocalDate.parse(input, formatter)

}
  • Related