Android Format Java Time/LocalDateTime to Localize Date String

October 4, 2019

Solution 1: DateUtil

val now = LocalDateTime.now()

Ommit year if current year

// 4 October
val text = DateUtils.formatDateTime(context, now.toMillis()!!, 0)

Show year if not current year

// 4 October 2018
val now = LocalDateTime.now().minusYears(1)
val text = DateUtils.formatDateTime(context, now.toMillis()!!, 0)

Use abbreviation

// 4 Oct
val text = DateUtils.formatDateTime(context, now.toMillis()!!, DateUtils.FORMAT_ABBREV_ALL)

Use abbreviation + Force show year

// 4 Oct 2019
val text = DateUtils.formatDateTime(context, now.toMillis()!!, DateUtils.FORMAT_ABBREV_ALL or DateUtils.FORMAT_SHOW_YEAR)

NOTE: Refer LocalDateTime.toMillis

Solution 2: DateTimeFormatter

val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
// 4 Oct 2019
val text = now.format(formatter)
val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
// 4 October 2019
val text = now.format(formatter)
val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
// 04/10/2019
val text = now.format(formatter)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.