@@ -2,12 +2,13 @@ package to.bitkit.models.widget
22
33import kotlinx.serialization.Serializable
44import to.bitkit.data.dto.ArticleDTO
5+ import to.bitkit.ext.toRelativeTimeString
56import to.bitkit.utils.Logger
67import java.time.OffsetDateTime
78import java.time.format.DateTimeFormatter
89import java.time.format.DateTimeParseException
9- import java.time.temporal.ChronoUnit
1010import java.util.Locale
11+ import kotlin.time.ExperimentalTime
1112
1213private const val TAG = " ArticleModel"
1314
@@ -26,14 +27,9 @@ fun ArticleDTO.toArticleModel() = ArticleModel(
2627 publisher = this .publisher.title
2728)
2829
29- /* *
30- * Converts a date string to a human-readable time ago format
31- * @param dateString Date string in format "EEE, dd MMM yyyy HH:mm:ss Z"
32- * @return Human-readable time difference (e.g. "5 hours ago")
33- */
34- @Suppress(" TooGenericExceptionCaught" , " MagicNumber" )
30+ @OptIn(ExperimentalTime ::class )
3531private fun timeAgo (dateString : String ): String {
36- return try {
32+ return runCatching {
3733 val formatters = listOf (
3834 DateTimeFormatter .RFC_1123_DATE_TIME , // Handles "EEE, dd MMM yyyy HH:mm:ss zzz" (like GMT)
3935 DateTimeFormatter .ofPattern(" EEE, dd MMM yyyy HH:mm:ss Z" , Locale .ENGLISH ) // Handles "+0000"
@@ -44,32 +40,15 @@ private fun timeAgo(dateString: String): String {
4440 try {
4541 parsedDateTime = OffsetDateTime .parse(dateString, formatter)
4642 break // Successfully parsed, stop trying other formatters
47- } catch (e : DateTimeParseException ) {
48- // Continue to the next formatter if this one fails
43+ } catch (_ : DateTimeParseException ) {
44+ // Continue to the next formatter
4945 }
5046 }
5147
52- if (parsedDateTime == null ) {
53- Logger .debug(" Failed to parse date: Unparseable date: $dateString " , context = TAG )
54- return " "
55- }
56-
57- val now = OffsetDateTime .now()
48+ requireNotNull(parsedDateTime) { " Unparseable date: '$dateString '" }
5849
59- val diffMinutes = ChronoUnit .MINUTES .between(parsedDateTime, now)
60- val diffHours = ChronoUnit .HOURS .between(parsedDateTime, now)
61- val diffDays = ChronoUnit .DAYS .between(parsedDateTime, now)
62- val diffMonths = ChronoUnit .MONTHS .between(parsedDateTime, now)
63-
64- return when {
65- diffMinutes < 1 -> " just now"
66- diffMinutes < 60 -> " $diffMinutes minutes ago"
67- diffHours < 24 -> " $diffHours hours ago"
68- diffDays < 30 -> " $diffDays days ago" // Approximate for months
69- else -> " $diffMonths months ago"
70- }
71- } catch (e: Exception ) {
72- Logger .warn(" An unexpected error occurred while parsing date" , e = e, context = TAG )
73- " "
74- }
50+ parsedDateTime.toInstant().toEpochMilli().toRelativeTimeString()
51+ }.onFailure {
52+ Logger .warn(" Failed to parse date: ${it.message} " , it, context = TAG )
53+ }.getOrDefault(" " )
7554}
0 commit comments