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

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