Khantahr
Khantahr

Reputation: 8548

Best Way to Format Time Respecting Locale and User's 24-hour Preference

I want to format a time display to conform to both the current Locale, and the device user's 24-hour clock preference. Here is what I'm currently doing, but I'm wondering if there's a better way.

val time = ZonedDateTime.now()
val formatter = when (DateFormat.is24HourFormat(context)) {
    true -> DateTimeFormatter.ofPattern("HH:mm", Locale.getDefault())
    false -> DateTimeFormatter.ofPattern("h:mm a", Locale.getDefault())
}

text = time.format(formatter)

Is there any way to get the user's 24 hour preference aside from using DateFormat (since that class is obsolete)?

Is there a better way to create the formatter? DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) doesn't respect the user's 24 hour preference.

Upvotes: 4

Views: 1129

Answers (1)

Bryan
Bryan

Reputation: 15155

Probably not the best solution, but this is what I came up with. It should retain any locale-specific formatting (as in the comment by @HeysemKatibi) while switching between 12 and 24-hour formats, but I haven't tested it throughly.

Really wish DateTimeFormatter respected the user settings and/or there was an easy way to tell it to switch to 24-hour time.

fun Context.formatTime(time: TemporalAccessor): String {
    var pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        null,
        FormatStyle.SHORT,
        IsoChronology.INSTANCE,
        Locale.getDefault()
    )

    if (DateFormat.is24HourFormat(this)) {
        pattern = pattern.replace("h", "H")
            .replace("a", "").trim()
    }

    val formatter = DateTimeFormatter.ofPattern(pattern)

    return formatter.format(time)
}

Upvotes: 4

Related Questions