Convert a Date (absolute time) to be sent/received across the network as Data in Swift?

You can send your Date converting it to Data (8-bytes floating point) and back to Date as follow:

extension Numeric {
    var data: Data {
        var source = self
        return .init(bytes: &source, count: MemoryLayout<Self>.size)
    }
    init<D: DataProtocol>(_ data: D) {
        var value: Self = .zero
        let size = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} )
        assert(size == MemoryLayout.size(ofValue: value))
        self = value
    }
}

extension UInt64 {
    var bitPattern: Double { .init(bitPattern: self) }
}

extension Date {
    var data: Data { timeIntervalSinceReferenceDate.bitPattern.littleEndian.data }
    init<D: DataProtocol>(data: D) {
        self.init(timeIntervalSinceReferenceDate: data.timeIntervalSinceReferenceDate)
    }
}

extension DataProtocol {
    func value<N: Numeric>() -> N { .init(self) }
    var uint64: UInt64 { value() }
    var timeIntervalSinceReferenceDate: TimeInterval { uint64.littleEndian.bitPattern }
    var date: Date { .init(data: self) }
}

Playground Testing

let date = Date()            // "Nov 15, 2019 at 12:13 PM"
let data = date.data         // 8 bytes
print(Array(data))           // "[25, 232, 158, 22, 124, 191, 193, 65]\n"
let loadedDate = data.date   // "Nov 15, 2019 at 12:13 PM"
print(date == loadedDate)    // "true"

Leave a Comment