Formatting.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/Formatting.kt
1package eu.friedcutlet.yokan.ui23import eu.friedcutlet.yokan.database.DbSettings4import eu.friedcutlet.yokan.util.nowMillis5import kotlin.time.Instant6import kotlinx.datetime.LocalDate7import kotlinx.datetime.LocalDateTime8import kotlinx.datetime.TimeZone9import kotlinx.datetime.atStartOfDayIn10import kotlinx.datetime.toLocalDateTime1112/**13 * Format an epoch-millis timestamp using the user's preferences from settings.14 *15 * - [DbSettings.relativeTimesTamps]:16 * * 0 — Off: always show the absolute date in [DbSettings.dateFormat].17 * * 1 — Short: show Today / Yesterday.18 * * 2 — Long: show Today / Yesterday / N days ago for entries within the19 * last week.20 * Both relative modes fall back to the absolute date outside their relative21 * window so timestamps stay unambiguous.22 *23 * Returns "—" if [epochMillis] is non-positive (uninitialised/never-set).24 */25fun formatTimestamp(26 epochMillis: Long,27 dateFormat: String,28 relativeMode: Int,29 now: Long = nowMillis(),30): String {31 if (epochMillis <= 0L) return "—"32 val normalizedEpochMillis = normalizeEpochMillis(epochMillis)33 if (relativeMode != 0) {34 val date = epochToLocalDate(normalizedEpochMillis).date35 val today = epochToLocalDate(now).date36 val deltaDays = ((startOfDayMillis(today) - startOfDayMillis(date)) / 86_400_000L).toInt()37 when {38 deltaDays == 0 -> return "Today"39 deltaDays == 1 -> return "Yesterday"40 relativeMode == 2 && deltaDays in 2..6 -> return "$deltaDays days ago"41 relativeMode == 2 && deltaDays == 7 -> return "A week ago"42 }43 }44 return formatAbsoluteDate(normalizedEpochMillis, dateFormat)45}4647/** Top-level convenience: format using the user's settings. */48fun formatTimestamp(settings: DbSettings, epochMillis: Long): String =49 formatTimestamp(epochMillis, settings.dateFormat, settings.relativeTimesTamps)5051/** Clock-only timestamp used by Mangayomi's history rows. */52fun formatClockTime(epochMillis: Long): String {53 if (epochMillis <= 0L) return "—"54 val local = epochToLocalDate(normalizeEpochMillis(epochMillis))55 return "${local.hour.pad2()}:${local.minute.pad2()}"56}5758/**59 * Format [epochMillis] as a date using the user-visible values from the60 * Appearance settings picker.61 *62 * The format string is the user-visible value from the settings picker. Any63 * unrecognised pattern falls back to ISO `yyyy-MM-dd` so we never crash on a64 * malformed value in storage.65 */66fun formatAbsoluteDate(epochMillis: Long, pattern: String): String {67 val ld = epochToLocalDate(normalizeEpochMillis(epochMillis))68 val month = ld.month.ordinal + 169 val day = ld.day70 return when (pattern) {71 "M/d/y" -> "$month/$day/${ld.year}"72 "d/M/y" -> "$day/$month/${ld.year}"73 "y/M/d" -> "${ld.year}/$month/$day"74 "MM/dd/yy" -> "${month.pad2()}/${day.pad2()}/${ld.year.twoDigitYear()}"75 "dd/MM/yy" -> "${day.pad2()}/${month.pad2()}/${ld.year.twoDigitYear()}"76 "MM/dd/yyyy" -> "${month.pad2()}/${day.pad2()}/${ld.year}"77 "dd/MM/yyyy" -> "${day.pad2()}/${month.pad2()}/${ld.year}"78 "yyyy/MM/dd" -> "${ld.year}/${month.pad2()}/${day.pad2()}"79 "yyyy-MM-dd" -> "${ld.year}-${month.pad2()}-${day.pad2()}"80 "dd MMM yyyy" -> "${day.pad2()} ${monthShort(month)} ${ld.year}"81 "MMM d, y" -> "${monthShort(month)} $day, ${ld.year}"82 "MMM d, yyyy" -> "${monthShort(month)} $day, ${ld.year}"83 "MMM dd, yyyy" -> "${monthShort(month)} ${day.pad2()}, ${ld.year}"84 "MMMM d, yyyy" -> "${monthLong(month)} $day, ${ld.year}"85 else -> "${ld.year}-${month.pad2()}-${day.pad2()}"86 }87}8889fun parseDateToEpochMillis(raw: String): Long? {90 val value = raw.trim()91 if (value.isBlank()) return null92 value.toLongOrNull()?.let { return normalizeEpochMillis(it) }93 val isoMatch = Regex("""(\d{4})-(\d{1,2})-(\d{1,2})""").find(value) ?: return null94 val (year, month, day) = isoMatch.destructured95 return runCatching {96 LocalDate(year.toInt(), month.toInt(), day.toInt())97 .atStartOfDayIn(TimeZone.currentSystemDefault())98 .toEpochMilliseconds()99 }.getOrNull()100}101102private fun normalizeEpochMillis(value: Long): Long {103 val abs = kotlin.math.abs(value)104 return if (abs in 1L until 10_000_000_000L) value * 1000L else value105}106107private fun startOfDayMillis(date: LocalDate): Long =108 date.atStartOfDayIn(TimeZone.currentSystemDefault()).toEpochMilliseconds()109110fun formatDecimal(value: Double, decimals: Int): String {111 val places = decimals.coerceAtLeast(0)112 var factor = 1L113 repeat(places) { factor *= 10L }114115 val sign = if (value < 0) "-" else ""116 val scaled = kotlin.math.round(kotlin.math.abs(value) * factor).toLong()117 val whole = scaled / factor118 if (places == 0) return "$sign$whole"119120 val fraction = (scaled % factor).toString().padStart(places, '0')121 return "$sign$whole.$fraction"122}123124@OptIn(kotlin.time.ExperimentalTime::class)125private fun epochToLocalDate(epochMillis: Long): LocalDateTime {126 val instant = Instant.fromEpochMilliseconds(epochMillis)127 return instant.toLocalDateTime(TimeZone.currentSystemDefault())128}129130private fun monthShort(month: Int): String = when (month) {131 1 -> "Jan"; 2 -> "Feb"; 3 -> "Mar"; 4 -> "Apr"; 5 -> "May"; 6 -> "Jun"132 7 -> "Jul"; 8 -> "Aug"; 9 -> "Sep"; 10 -> "Oct"; 11 -> "Nov"; 12 -> "Dec"133 else -> month.toString()134}135136private fun monthLong(month: Int): String = when (month) {137 1 -> "January"; 2 -> "February"; 3 -> "March"; 4 -> "April"; 5 -> "May"; 6 -> "June"138 7 -> "July"; 8 -> "August"; 9 -> "September"; 10 -> "October"; 11 -> "November"; 12 -> "December"139 else -> month.toString()140}141142private fun Int.pad2(): String = if (this < 10) "0$this" else toString()143144private fun Int.twoDigitYear(): String = (this % 100).pad2()145