SyncTimeUtils.swift 30 lignes · 1256 octets
import Foundation

/// ISO-8601 UTC → epoch ms, tolerant to absent/invalid values (mirror of server `mis_a_jour_le` timestamps).
func parseIsoToEpochMs(_ iso: String?) -> Int64 {
    guard let iso else { return 0 }
    let withFraction = ISO8601DateFormatter()
    withFraction.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    if let date = withFraction.date(from: iso) {
        return Int64((date.timeIntervalSince1970 * 1000).rounded())
    }
    let plain = ISO8601DateFormatter()
    plain.formatOptions = [.withInternetDateTime]
    if let date = plain.date(from: iso) {
        return Int64((date.timeIntervalSince1970 * 1000).rounded())
    }
    return 0
}

/// epoch ms → ISO-8601 UTC, for payloads pushed to the server (`debut`/`fin`).
/// Mirrors Kotlin `Instant.ofEpochMilli(ms).toString()`: no fraction when ms is whole seconds.
func epochMsToIso(_ epochMs: Int64) -> String {
    let date = Date(timeIntervalSince1970: Double(epochMs) / 1000.0)
    let formatter = ISO8601DateFormatter()
    if epochMs % 1000 == 0 {
        formatter.formatOptions = [.withInternetDateTime]
    } else {
        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    }
    return formatter.string(from: date)
}