2

I have a string, e.g. "mon" or "tue" or "sun". I want to parse it as a DayOfWeek (or null if not successful).

I'm using Kotlin, but i guess the Java folks will also understand what i would like to do:

private fun String.parseToDayOfWeek(pattern: String = "EE") =
    try {
        DateTimeFormatter.ofPattern(pattern, Locale.US).parse(this, DayOfWeek::from)
    } catch (e: Exception){
        null
    }

This doesn't work, i'm just getting nulls.

Instead i have to sanitize the string like this before i parse it:

val capitalized = this.lowercase().replaceFirstChar { it.uppercase() }

This feels cumbersome. Am i using the api wrong or is this a hefty stumbling block?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
m.reiter
  • 1,796
  • 2
  • 11
  • 31
  • In some locales, a day-of-week name is expected to be all lowercase while in others an initial-cap is expected. In the United States, the initial-cap is expected: Mon, Tue, not mon, tue. – Basil Bourque Jul 05 '21 at 22:54

2 Answers2

6

You have to use a DateTimeFormatterBuilder and set the parseCaseInsensitive:

private fun String.parseToDayOfWeek(pattern: String = "EE") =
try {
    val formatter = DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern(pattern)
        .toFormatter(Locale.US);

    formatter.parse(this, DayOfWeek::from)
} catch (e: Exception){
    null
}
1

You're not using it wrong afaics. It seems that a lower case beginning is not allowed

g00se
  • 3,207
  • 2
  • 5
  • 9