Skip to content

Commit

Permalink
Locale-aware date formatting for desktop (#1159)
Browse files Browse the repository at this point in the history
It's not a complete solution - just localization for default m3
skeletons. User-provided variants will still be ugly :(

Before and after:

<img width="300" alt="Снимок экрана 2024-02-29 в 21 17 28"
src="https://github.com/JetBrains/compose-multiplatform-core/assets/63979218/4560e92d-f0a4-4d0b-85bb-34756dd5a938">

<img width="300" alt="Screenshot 2024-03-04 at 17 22 51"
src="https://github.com/JetBrains/compose-multiplatform-core/assets/63979218/eef72277-8bbe-4edf-bc6b-a5b7d0085634">
  • Loading branch information
alexzhirkevich committed Mar 15, 2024
1 parent 73be0df commit 230923f
Showing 1 changed file with 19 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,14 @@ package androidx.compose.material3
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.time.DayOfWeek
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.format.TextStyle


@OptIn(ExperimentalMaterial3Api::class)
internal actual class PlatformDateFormat actual constructor(private val locale: CalendarLocale) {
private val delegate = LegacyCalendarModelImpl(locale)

Expand All @@ -40,18 +45,26 @@ internal actual class PlatformDateFormat actual constructor(private val locale:
skeleton: String
): String {
// Note: there is no equivalent in Java for Android's DateFormat.getBestDateTimePattern.
// The JDK SimpleDateFormat expects a pattern, so the results will be "2023Jan7",
// The JDK SimpleDateFormat expects a pattern, so the results for unrecognized skeletons will be "2023Jan7",
// "2023January", etc. in case a skeleton holds an actual ICU skeleton and not a pattern.

// TODO: support ICU skeleton on JVM
// Maybe it will be supported in kotlinx.datetime in the future.
// See https://github.com/Kotlin/kotlinx-datetime/pull/251

// stub: not localized but at least readable variant
val pattern = when(skeleton){
DatePickerDefaults.YearMonthSkeleton -> "MMMM yyyy"
DatePickerDefaults.YearAbbrMonthDaySkeleton -> "MMM d, yyyy"
DatePickerDefaults.YearMonthWeekdayDaySkeleton -> "EEEE, MMMM d, yyyy"
DatePickerDefaults.YearAbbrMonthDaySkeleton -> {
return DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.localizedBy(locale)
.format(Instant.ofEpochMilli(utcTimeMillis).atOffset(ZoneOffset.UTC))
}
DatePickerDefaults.YearMonthWeekdayDaySkeleton -> {
return DateTimeFormatter
.ofLocalizedDate(FormatStyle.FULL)
.localizedBy(locale)
.format(Instant.ofEpochMilli(utcTimeMillis).atOffset(ZoneOffset.UTC))
}
DatePickerDefaults.YearMonthSkeleton -> "LLLL yyyy" // L is a pattern for standalone month (without day)
else -> skeleton
}
return formatWithPattern(utcTimeMillis, pattern)
Expand Down

0 comments on commit 230923f

Please sign in to comment.