forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresData+Date.swift
58 lines (51 loc) · 1.82 KB
/
PostgresData+Date.swift
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
57
58
import Foundation
extension PostgresData {
public init(date: Date) {
var buffer = ByteBufferAllocator().buffer(capacity: 0)
let seconds = date.timeIntervalSince(_psqlDateStart) * Double(_microsecondsPerSecond)
buffer.writeInteger(Int64(seconds))
self.init(type: .timestamptz, value: buffer)
}
public var date: Date? {
guard var value = self.value else {
return nil
}
switch self.formatCode {
case .text:
return nil
case .binary:
switch self.type {
case .timestamp, .timestamptz:
let microseconds = value.readInteger(as: Int64.self)!
let seconds = Double(microseconds) / Double(_microsecondsPerSecond)
return Date(timeInterval: seconds, since: _psqlDateStart)
case .time, .timetz:
return nil
case .date:
let days = value.readInteger(as: Int32.self)!
let seconds = Int64(days) * _secondsInDay
return Date(timeInterval: Double(seconds), since: _psqlDateStart)
default:
return nil
}
}
}
}
extension Date: PostgresDataConvertible {
public static var postgresDataType: PostgresDataType {
return .timestamptz
}
public init?(postgresData: PostgresData) {
guard let date = postgresData.date else {
return nil
}
self = date
}
public var postgresData: PostgresData? {
return .init(date: self)
}
}
// MARK: Private
private let _microsecondsPerSecond: Int64 = 1_000_000
private let _secondsInDay: Int64 = 24 * 60 * 60
private let _psqlDateStart = Date(timeIntervalSince1970: 946_684_800) // values are stored as seconds before or after midnight 2000-01-01