Home > Back-end >  Kotlin parse `MMYYYY` into YearMonth
Kotlin parse `MMYYYY` into YearMonth

Time:06-10

I want to parse a MMYYYY field to YearMonth in kotlin.

Example tried :

import java.time.YearMonth
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder

val formatter: DateTimeFormatter = DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("MMYYYY")
            .toFormatter(Locale.ENGLISH)

println(YearMonth.parse("011970", formatter))

it didn't work

CodePudding user response:

Your pattern is incorrect, it uses the symbol for week based year (Y) instead of year (u) or maybe year of era (y).

Read more about the symbols in the JavaDocs of DateTimeFormatter, some of them relevant here are:

Symbol Meaning Presentation Examples
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
M/L month-of-year number/text 7; 07; Jul; July; J
Y week-based-year year 1996; 96

I'd recommend you switch to year:

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

val formatter: DateTimeFormatter = DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("MMuuuu")
            .toFormatter(Locale.ENGLISH)

fun main() {
    println(YearMonth.parse("011970", formatter))
}

This code prints 1970-01

Iif you are sure you will exclusively receive numerical Strings, you can also use a less complex DateTimeFormatter by leaving the check for case sensitivity:

val formatter = DateTimeFormatter.ofPattern("MMuuuu", Locale.ENGLISH)
  • Related