Reputation: 2525
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 null
s.
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?
Upvotes: 2
Views: 479
Reputation: 198
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
}
Upvotes: 6
Reputation: 4296
You're not using it wrong afaics. It seems that a lower case beginning is not allowed
Upvotes: 1