2022-11-25 11:00:01 +00:00
|
|
|
import Foundation
|
2022-11-25 09:03:42 +00:00
|
|
|
|
2023-02-12 15:29:41 +00:00
|
|
|
private enum CodingKeys: CodingKey {
|
2023-02-09 18:25:12 +00:00
|
|
|
case asDate
|
2023-02-09 08:12:44 +00:00
|
|
|
}
|
2022-12-17 12:37:46 +00:00
|
|
|
|
2023-02-18 21:51:44 +00:00
|
|
|
public struct ServerDate: Codable, Hashable, Equatable, Sendable {
|
2023-02-09 08:12:44 +00:00
|
|
|
public let asDate: Date
|
2023-12-28 11:31:16 +00:00
|
|
|
private let isOlderThanADay: Bool
|
2023-02-12 15:29:41 +00:00
|
|
|
|
2023-02-09 18:25:12 +00:00
|
|
|
public var relativeFormatted: String {
|
2023-12-27 17:05:41 +00:00
|
|
|
let date = asDate
|
2023-12-28 11:31:16 +00:00
|
|
|
if isOlderThanADay {
|
2023-12-27 17:05:41 +00:00
|
|
|
return DateFormatterCache.shared.createdAtRelativeFormatter.localizedString(for: date,
|
|
|
|
relativeTo: Date())
|
|
|
|
} else {
|
|
|
|
return Duration.seconds(-date.timeIntervalSinceNow).formatted(.units(width: .narrow,
|
2024-02-14 11:48:14 +00:00
|
|
|
maximumUnitCount: 1))
|
2023-12-27 17:05:41 +00:00
|
|
|
}
|
2023-02-09 18:25:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public var shortDateFormatted: String {
|
2023-09-15 10:46:15 +00:00
|
|
|
DateFormatterCache.shared.createdAtShortDateFormatted.string(from: asDate)
|
2023-02-09 18:25:12 +00:00
|
|
|
}
|
2024-02-14 11:48:14 +00:00
|
|
|
|
2023-02-09 08:12:44 +00:00
|
|
|
private static let calendar = Calendar(identifier: .gregorian)
|
2023-02-12 15:29:41 +00:00
|
|
|
|
2023-02-09 08:12:44 +00:00
|
|
|
public init() {
|
2023-02-12 15:29:41 +00:00
|
|
|
asDate = Date() - 100
|
2023-12-28 11:31:16 +00:00
|
|
|
isOlderThanADay = false
|
2022-11-25 09:03:42 +00:00
|
|
|
}
|
2023-02-12 15:29:41 +00:00
|
|
|
|
2023-02-09 08:12:44 +00:00
|
|
|
public init(from decoder: Decoder) throws {
|
|
|
|
do {
|
|
|
|
// Decode from server
|
|
|
|
let container = try decoder.singleValueContainer()
|
|
|
|
let stringDate = try container.decode(String.self)
|
2023-09-15 10:46:15 +00:00
|
|
|
asDate = DateFormatterCache.shared.createdAtDateFormatter.date(from: stringDate) ?? Date()
|
2023-02-09 08:12:44 +00:00
|
|
|
} catch {
|
|
|
|
// Decode from cache
|
|
|
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
|
|
|
asDate = try container.decode(Date.self, forKey: .asDate)
|
|
|
|
}
|
2024-02-14 11:48:14 +00:00
|
|
|
|
2023-12-28 11:31:16 +00:00
|
|
|
let aDay: TimeInterval = 60 * 60 * 24
|
|
|
|
isOlderThanADay = Date().timeIntervalSince(asDate) >= aDay
|
2022-12-16 12:16:48 +00:00
|
|
|
}
|
2023-02-12 15:29:41 +00:00
|
|
|
|
2023-02-09 08:12:44 +00:00
|
|
|
public func encode(to encoder: Encoder) throws {
|
|
|
|
var container = encoder.container(keyedBy: CodingKeys.self)
|
|
|
|
try container.encode(asDate, forKey: .asDate)
|
2022-11-25 11:00:01 +00:00
|
|
|
}
|
2022-11-25 09:03:42 +00:00
|
|
|
}
|