How to use Locale in LocalDateTime?

Viewed 128

I'm using this extension-function for getting day of week:

private fun WeatherList.getDayOfWeek() =
        LocalDateTime.ofEpochSecond(dt.toLong(), 0, ZoneOffset.UTC).toLocalDate().dayOfWeek

dt - date time in my class in Unix

WeatherList is my class:

@Serializable
@Parcelize
data class WeatherList(
    val dt: Int,
    val main: Main,
    val weather: List<Weather>,
    val clouds: Clouds,
    val wind: Wind,
    val visibility: Int,
    val pop: Double,
    val sys: Sys,
    val dt_txt: String,
) : Parcelable

I was thinking that this should use Locale for output day of week but it's always English. So how to use locale language for day of week?

1 Answers

Here's an example that takes a Locale and the epoch seconds as arguments and returns the name of the week as common in that specific Locale:

import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.TextStyle;
import java.util.Locale

fun WeatherList.getDayOfWeekName(locale: Locale, epochSecs: Int): String {
    return LocalDateTime.ofEpochSecond(epochSecs.toLong(), 0, ZoneOffset.UTC)
                        .dayOfWeek
                        .getDisplayName(TextStyle.FULL, locale);
}

You can of course include a fixed Locale and directly reference some variable holding the epoch seconds, but especially the last line gives you the name of the day of week in the given Locale's language and format.

Passing Locale.GERMAN and the epoch seconds 1631264387 would return Freitag (that's a German Friday).

Related