1

I'm working with a String of date such as:

 val date = "2021-01-24"

how can I convert that string in order to get "Sunday" (user local english) or "Domingo" (user local spanish)?

// Error I get using Dai answer

java.lang.IllegalArgumentException: Cannot format given Object as a Date

I'm using this code:

// Step 1: Parse the string with a defined format:

val tomorrowDateString = body.forecast.forecastday[1].date // -> "2021-01-24"
val parseTomorrow = LocalDate.parse(tomorrowDateString, DateTimeFormatter.ofPattern( "yyyy-MM-dd" ))

// Step 2: Format using the user's culture/locale settings:

val userFormat = java.text.DateFormat.getDateInstance( DateFormat.SHORT )
val tomorrow = userFormat.format(parseTomorrow)
  • Parse the string to a datetime value, then format the datetime value using the user's current culture: https://www.baeldung.com/kotlin/dates – Dai Jan 24 '21 at 14:25

2 Answers2

0

Date formatting based on user locale on android

// Step 1: Parse the string with a defined format:
val input    = "2021-01-24"
val parsedDt = LocalDate.parse( input , DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) )

// Step 2: Format using the user's culture/locale settings:
val userFormat = java.text.DateFormat.getDateInstance( DateFormat.SHORT )
val formatted  = userFormat.format( parsedDt )
Dai
  • 141,631
  • 28
  • 261
  • 374
  • Thanks Dai, I'm getting an error doing that, I don't understand why. I've edited my post with the code I'm using. Thanks again! – Kevin Buguecio Jan 24 '21 at 14:56
  • Are you certain that `tomorrowDateString` is a `String` and not some other type? Notice that the error message describes it as an `Object`. – Dai Jan 24 '21 at 16:58
  • I've checked it in console and it says that `tomorrowDateString` is a `String`. `val tomorrowDateString = body.forecast.forecastday[1].date` --> `Log.d("Type", tomorrowDateString.javaClass.kotlin.qualifiedName)` and it logs `D/Type: kotlin.String` – Kevin Buguecio Jan 24 '21 at 19:15
  • I'm also trying to run just the code you shared me and it crashes with the same error. that `Cannot format given Object as a Date` – Kevin Buguecio Jan 24 '21 at 19:54
0

I've managed to solve my question using another similar approach.

//Get user local language
var currentLang = Locale.getDefault().language

val dateString = "2021-01-24"
val parsedDate = LocalDate.parse(dateString)

val dateAsDayOfWeek = parsedDate.dayOfWeek.getDisplayName(TextStyle.FULL, Locale(currentLang))

Log.d("Date", dateAsDayOfWeek)

//Logs -> "sunday" if local language is English, "domingo" if local is Spanish, etc...