Search code examples
javajava-timedayofweekdate-parsinglocaldatetime

Parse lowercase short weekday to Java 8's time DayOfWeek


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?


Solution

  • 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
    }