-
Notifications
You must be signed in to change notification settings - Fork 1
/
Date+Formatting.swift
92 lines (74 loc) · 2.71 KB
/
Date+Formatting.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// @copyright Trollwerks Inc.
import Foundation
extension Date {
var toLocalTime: Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
var toUTC: Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
}
extension DateFormatter {
static let fbDay = DateFormatter {
$0.dateFormat = "MM/dd/yyyy"
$0.calendar = Calendar(identifier: .iso8601)
$0.timeZone = TimeZone(secondsFromGMT: 0)
$0.locale = Locale(identifier: "en_US_POSIX")
}
static let mtpDay = DateFormatter {
$0.dateFormat = "yyyy-MM-dd"
$0.calendar = Calendar(identifier: .iso8601)
$0.timeZone = TimeZone(secondsFromGMT: 0)
$0.locale = Locale(identifier: "en_US_POSIX")
}
static let mtpLocalDay = DateFormatter {
$0.dateFormat = "yyyy-MM-dd"
$0.calendar = Calendar(identifier: .iso8601)
$0.timeZone = TimeZone.current
$0.locale = Locale(identifier: "en_US_POSIX")
}
static let mtpTime = DateFormatter {
$0.dateFormat = "yyyy-MM-dd HH:mm:ss"
$0.calendar = Calendar(identifier: .iso8601)
$0.timeZone = TimeZone(secondsFromGMT: 0)
$0.locale = Locale(identifier: "en_US_POSIX")
}
static var stampTime = DateFormatter {
$0.dateFormat = "yy.MM.dd HH:mm:ss.SSS"
$0.calendar = Calendar(identifier: .iso8601)
$0.timeZone = TimeZone.current
$0.locale = Locale(identifier: "en_US_POSIX")
}
static let mtpBirthday = DateFormatter(mtp: .medium)
static let mtpPost = DateFormatter(mtp: .long)
convenience init(mtp style: DateFormatter.Style) {
self.init()
dateStyle = style
timeStyle = .none
timeZone = TimeZone(secondsFromGMT: 0)
}
}
extension JSONDecoder {
static let mtp: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
if let date = DateFormatter.mtpDay.date(from: dateString) {
return date
}
if let date = DateFormatter.mtpTime.date(from: dateString) {
return date
}
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Cannot decode date: '\(dateString)'")
}
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
}