library: add DateString date/time formatter, remove unused DateFormats
- Commit
ef836ba451d07475f3aca4bb76d6e416c6f64c1d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-10 18:38 UTC (3 months ago)
- Parents
02f6141
Diff
library/ui/src/main/java/com/vayunmathur/library/ui/DateFormats.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/DateFormats.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/DateFormats.ktdeleted file mode 100644index 8fddb9cd28..0000000000--- a/library/ui/src/main/java/com/vayunmathur/library/ui/DateFormats.kt+++ /dev/null@@ -1,74 +0,0 @@-package com.vayunmathur.library.ui--import android.content.Context-import android.text.format.DateFormat-import androidx.compose.runtime.Composable-import androidx.compose.ui.platform.LocalConfiguration-import androidx.compose.ui.platform.LocalContext-import kotlin.time.Instant-import java.time.ZonedDateTime-import java.time.ZoneId-import java.time.format.DateTimeFormatter-import java.time.format.FormatStyle-import java.util.Locale--/**- * Date and time formatting.- *- * Seven apps were on `SimpleDateFormat`, two on `DateTimeFormatter`, and eight- * on the shared `localizedMonthNames`. `SimpleDateFormat` is the one to get- * away from: it is mutable and not thread-safe, so a shared instance corrupts- * its own output under concurrency, and it does not follow the user's- * 12/24-hour system setting the way [DateFormat.is24HourFormat] does.- *- * These follow the locale for date order and the system setting for the clock,- * which is what users expect and what neither of the other two approaches did- * consistently.- */-object DateFormats {-- // Via epoch millis rather than a kotlinx-datetime interop conversion:- // the apps mix kotlin.time.Instant and java.time.Instant, and this needs- // neither to be on the classpath of the caller.- private fun zoned(instant: Instant): ZonedDateTime =- java.time.Instant.ofEpochMilli(instant.toEpochMilliseconds())- .atZone(ZoneId.systemDefault())-- /** Date only, in the locale's short form - 3/14/25, 14/03/2025. */- fun date(instant: Instant, locale: Locale = Locale.getDefault()): String =- DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)- .withLocale(locale)- .format(zoned(instant))-- /** Date in a longer, readable form - 14 March 2025. */- fun dateLong(instant: Instant, locale: Locale = Locale.getDefault()): String =- DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)- .withLocale(locale)- .format(zoned(instant))-- /** Time of day, honouring the system 12/24-hour setting. */- fun time(- context: Context,- instant: Instant,- locale: Locale = Locale.getDefault(),- ): String {- val pattern = if (DateFormat.is24HourFormat(context)) "HH:mm" else "h:mm a"- return DateTimeFormatter.ofPattern(pattern, locale).format(zoned(instant))- }-- /** Date and time together. */- fun dateTime(- context: Context,- instant: Instant,- locale: Locale = Locale.getDefault(),- ): String = "${date(instant, locale)} ${time(context, instant, locale)}"-}--/** [DateFormats.time] using the ambient context and locale. */-@Composable-fun rememberTimeText(instant: Instant): String {- val context = LocalContext.current- @Suppress("DEPRECATION")- val locale = LocalConfiguration.current.locales[0]- return DateFormats.time(context, instant, locale)-}
library/ui/src/main/java/com/vayunmathur/library/ui/DateString.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/DateString.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/DateString.ktnew file mode 100644index 0000000000..e7bed27961--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/DateString.kt@@ -0,0 +1,222 @@+package com.vayunmathur.library.ui++import android.content.Context+import android.text.format.DateFormat+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.library.util.DateNameStyle+import com.vayunmathur.library.util.localizedAmPmMarker+import com.vayunmathur.library.util.localizedDayOfWeekNames+import com.vayunmathur.library.util.localizedMonthNames+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.LocalTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.format+import kotlinx.datetime.format.DayOfWeekNames+import kotlinx.datetime.format.MonthNames+import kotlinx.datetime.format.Padding+import kotlinx.datetime.format.char+import kotlinx.datetime.toJavaLocalDate+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant+import java.time.format.DateTimeFormatter+import java.time.format.FormatStyle+import java.util.Locale++/**+ * The one place dates and times get turned into display strings.+ *+ * Every app used to hand-build its own `LocalDate.Format {}` / `LocalTime.Format {}`+ * (or manual `"$day/$month"` interpolation), which meant locale-correct month and+ * weekday names, localized AM/PM markers, and the system 12/24-hour setting were+ * re-derived per app and occasionally gotten wrong. These helpers centralize the+ * calendar-date and clock-time shapes the apps actually render.+ *+ * Everything returns a [String] so the caller wraps it in its own `Text` — Material+ * in normal UI, `androidx.glance.text.Text` in a widget, or a `%s` placeholder in a+ * localized resource string.+ *+ * Locale-correct names come from+ * [com.vayunmathur.library.util.localizedMonthNames] /+ * [com.vayunmathur.library.util.localizedDayOfWeekNames] /+ * [com.vayunmathur.library.util.localizedAmPmMarker], the same ICU-backed helpers+ * kotlinx-datetime callers were already using.+ *+ * Out of scope by design: elapsed/countdown durations (timer, stopwatch, track+ * length) and relative time ("Today", "5 minutes ago") — those are not calendar+ * dates or clock times and keep their own formatters.+ */+object DateString {++ // ── Date-only forms (input LocalDate) ──────────────────────────────────++ /**+ * The locale's short numeric date — `3/14/25` in en-US, `14/03/25` in en-GB.+ *+ * The only form built on `java.time`: kotlinx-datetime has no locale-aware+ * field ordering, and `FormatStyle.SHORT` is exactly that ordering.+ */+ fun dateShort(date: LocalDate, locale: Locale = Locale.getDefault()): String =+ DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)+ .withLocale(locale)+ .format(date.toJavaLocalDate())++ /** A long, readable date — `14 March 2025`. */+ fun dateLong(date: LocalDate, locale: Locale = Locale.getDefault()): String =+ date.format(LocalDate.Format {+ day(Padding.NONE)+ char(' ')+ monthName(MonthNames(localizedMonthNames(DateNameStyle.FULL, locale)))+ char(' ')+ year()+ })++ /** Date with weekday and year — `Mon, Jan 3, 2025`. */+ fun dateWeekday(date: LocalDate, locale: Locale = Locale.getDefault()): String =+ date.format(LocalDate.Format {+ dayOfWeek(DayOfWeekNames(localizedDayOfWeekNames(DateNameStyle.SHORT, locale)))+ char(','); char(' ')+ monthName(MonthNames(localizedMonthNames(DateNameStyle.SHORT, locale)))+ char(' ')+ day(Padding.NONE)+ char(','); char(' ')+ year(Padding.NONE)+ })++ /** Date with weekday, no year — `Mon, Jan 3`. */+ fun dateWeekdayNoYear(date: LocalDate, locale: Locale = Locale.getDefault()): String =+ date.format(LocalDate.Format {+ dayOfWeek(DayOfWeekNames(localizedDayOfWeekNames(DateNameStyle.SHORT, locale)))+ char(','); char(' ')+ monthName(MonthNames(localizedMonthNames(DateNameStyle.SHORT, locale)))+ char(' ')+ day(Padding.NONE)+ })++ /** Date without a weekday — `Jan 3, 2025`. */+ fun monthDayYear(date: LocalDate, locale: Locale = Locale.getDefault()): String =+ date.format(LocalDate.Format {+ monthName(MonthNames(localizedMonthNames(DateNameStyle.SHORT, locale)))+ char(' ')+ day(Padding.NONE)+ char(','); char(' ')+ year()+ })++ // ── Time-only forms (input LocalTime + the 12/24-hour flag) ────────────++ /** Clock time honouring the 12/24-hour setting — `3:05 PM` / `15:05`. */+ fun time(+ time: LocalTime,+ is24Hour: Boolean,+ locale: Locale = Locale.getDefault(),+ ): String = time.format(LocalTime.Format {+ clock(is24Hour)+ if (!is24Hour) { char(' '); localizedAmPmMarker(locale) }+ })++ /** Clock time with seconds — `3:05:23 PM` / `15:05:23`. */+ fun timeSeconds(+ time: LocalTime,+ is24Hour: Boolean,+ locale: Locale = Locale.getDefault(),+ ): String = time.format(LocalTime.Format {+ clock(is24Hour, seconds = true)+ if (!is24Hour) { char(' '); localizedAmPmMarker(locale) }+ })++ /**+ * The numeric part of the time, no AM/PM marker — `3:05` / `15:05`.+ *+ * For call sites that render the marker separately (e.g. the clock's main+ * display styles the digits and the marker differently) or concatenate it+ * themselves with custom spacing.+ */+ fun timeNumeric(time: LocalTime, is24Hour: Boolean): String =+ time.format(LocalTime.Format { clock(is24Hour) })++ /** Numeric time with seconds, no AM/PM marker — `3:05:23` / `15:05:23`. */+ fun timeSecondsNumeric(time: LocalTime, is24Hour: Boolean): String =+ time.format(LocalTime.Format { clock(is24Hour, seconds = true) })++ /** A whole-hour axis label — `3 PM` / `15:00`. */+ fun hourLabel(+ time: LocalTime,+ is24Hour: Boolean,+ locale: Locale = Locale.getDefault(),+ ): String = time.format(LocalTime.Format {+ if (is24Hour) {+ hour(Padding.ZERO); char(':'); char('0'); char('0')+ } else {+ amPmHour(Padding.NONE); char(' '); localizedAmPmMarker(locale)+ }+ })++ /** [hourLabel] for a bare hour-of-day (0..23), for axis iteration. */+ fun hourLabel(+ hour: Int,+ is24Hour: Boolean,+ locale: Locale = Locale.getDefault(),+ ): String = hourLabel(LocalTime(hour, 0), is24Hour, locale)++ // ── Date + time (input LocalDateTime) ──────────────────────────────────++ /** Short date and clock time together — `3/14/25 3:05 PM` / `3/14/25 15:05`. */+ fun dateTime(+ dateTime: LocalDateTime,+ is24Hour: Boolean,+ locale: Locale = Locale.getDefault(),+ ): String = "${dateShort(dateTime.date, locale)} ${time(dateTime.time, is24Hour, locale)}"++ // ── Instant convenience overloads (the common forms) ───────────────────++ fun dateShort(+ instant: Instant,+ zone: TimeZone = TimeZone.currentSystemDefault(),+ locale: Locale = Locale.getDefault(),+ ): String = dateShort(instant.toLocalDateTime(zone).date, locale)++ fun dateLong(+ instant: Instant,+ zone: TimeZone = TimeZone.currentSystemDefault(),+ locale: Locale = Locale.getDefault(),+ ): String = dateLong(instant.toLocalDateTime(zone).date, locale)++ fun time(+ instant: Instant,+ is24Hour: Boolean,+ zone: TimeZone = TimeZone.currentSystemDefault(),+ locale: Locale = Locale.getDefault(),+ ): String = time(instant.toLocalDateTime(zone).time, is24Hour, locale)++ fun dateTime(+ instant: Instant,+ is24Hour: Boolean,+ zone: TimeZone = TimeZone.currentSystemDefault(),+ locale: Locale = Locale.getDefault(),+ ): String = dateTime(instant.toLocalDateTime(zone), is24Hour, locale)+}++// Shared "h:mm" / "HH:mm" (optionally with seconds) core so every time form+// stays consistent: 24h is zero-padded, 12h uses the non-padded am/pm hour.+private fun kotlinx.datetime.format.DateTimeFormatBuilder.WithTime.clock(+ is24Hour: Boolean,+ seconds: Boolean = false,+) {+ if (is24Hour) hour(Padding.ZERO) else amPmHour(Padding.NONE)+ char(':')+ minute()+ if (seconds) { char(':'); second() }+}++/** The device's 12/24-hour setting, for the string forms that need it. */+fun is24Hour(context: Context): Boolean = DateFormat.is24HourFormat(context)++/** [is24Hour] read from the ambient Compose context. */+@Composable+fun rememberIs24Hour(): Boolean {+ val context = LocalContext.current+ return remember { DateFormat.is24HourFormat(context) }+}
library/ui/src/test/java/com/vayunmathur/library/ui/DateStringTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/DateStringTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/DateStringTest.ktnew file mode 100644index 0000000000..dd0558e7fd--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/DateStringTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.library.ui++import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalTime+import java.util.Locale+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Covers the [DateString] forms that don't touch `android.icu` / `android.text.format`,+ * so they run on the plain-JVM unit-test classpath (this module has no Robolectric):+ *+ * - [DateString.dateShort] — locale-ordered date via `java.time`.+ * - [DateString.timeNumeric] / [DateString.timeSecondsNumeric] — pure kotlinx-datetime.+ *+ * The localized-name forms (weekday/month names, AM/PM markers) are exercised by the+ * app screens and manual/instrumented runs; the ICU stubs make them un-unit-testable here.+ */+class DateStringTest {++ private val pi = LocalDate(2025, 3, 14) // 14 March 2025++ @Test fun dateShortUsesLocaleFieldOrder() {+ assertEquals("3/14/25", DateString.dateShort(pi, Locale.US))+ assertEquals("14.03.25", DateString.dateShort(pi, Locale.GERMANY))+ }++ @Test fun timeNumeric24HourIsZeroPadded() {+ assertEquals("15:05", DateString.timeNumeric(LocalTime(15, 5), is24Hour = true))+ assertEquals("09:05", DateString.timeNumeric(LocalTime(9, 5), is24Hour = true))+ assertEquals("00:00", DateString.timeNumeric(LocalTime(0, 0), is24Hour = true))+ }++ @Test fun timeNumeric12HourDropsLeadingHourZero() {+ assertEquals("3:05", DateString.timeNumeric(LocalTime(15, 5), is24Hour = false))+ assertEquals("9:05", DateString.timeNumeric(LocalTime(9, 5), is24Hour = false))+ // Midnight and noon read as 12 in 12-hour form.+ assertEquals("12:00", DateString.timeNumeric(LocalTime(0, 0), is24Hour = false))+ assertEquals("12:30", DateString.timeNumeric(LocalTime(12, 30), is24Hour = false))+ }++ @Test fun timeSecondsNumericAppendsSeconds() {+ assertEquals("15:05:23", DateString.timeSecondsNumeric(LocalTime(15, 5, 23), is24Hour = true))+ assertEquals("3:05:23", DateString.timeSecondsNumeric(LocalTime(15, 5, 23), is24Hour = false))+ }+}