-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathArticleModel.kt
More file actions
56 lines (48 loc) · 1.75 KB
/
ArticleModel.kt
File metadata and controls
56 lines (48 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package to.bitkit.models.widget
import androidx.compose.runtime.Immutable
import kotlinx.serialization.Serializable
import to.bitkit.data.dto.ArticleDTO
import to.bitkit.ext.toRelativeTimeString
import to.bitkit.utils.Logger
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.util.Locale
import kotlin.time.ExperimentalTime
private const val TAG = "ArticleModel"
@Immutable
@Serializable
data class ArticleModel(
val title: String,
val timeAgo: String,
val link: String,
val publisher: String
)
fun ArticleDTO.toArticleModel() = ArticleModel(
title = this.title,
timeAgo = timeAgo(this.publishedDate),
link = this.link,
publisher = this.publisher.title
)
@OptIn(ExperimentalTime::class)
private fun timeAgo(dateString: String): String {
return runCatching {
val formatters = listOf(
DateTimeFormatter.RFC_1123_DATE_TIME, // Handles "EEE, dd MMM yyyy HH:mm:ss zzz" (like GMT)
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH) // Handles "+0000"
)
var parsedDateTime: OffsetDateTime? = null
for (formatter in formatters) {
try {
parsedDateTime = OffsetDateTime.parse(dateString, formatter)
break // Successfully parsed, stop trying other formatters
} catch (_: DateTimeParseException) {
// Continue to the next formatter
}
}
requireNotNull(parsedDateTime) { "Unparseable date: '$dateString'" }
parsedDateTime.toInstant().toEpochMilli().toRelativeTimeString()
}.onFailure {
Logger.warn("Failed to parse date: ${it.message}", it, context = TAG)
}.getOrDefault("")
}