forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNSDate.swift
470 lines (378 loc) · 16.7 KB
/
NSDate.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_implementationOnly import CoreFoundation
public typealias TimeInterval = Double
internal let kCFDateFormatterNoStyle = CFDateFormatterStyle.noStyle
internal let kCFDateFormatterShortStyle = CFDateFormatterStyle.shortStyle
internal let kCFDateFormatterMediumStyle = CFDateFormatterStyle.mediumStyle
internal let kCFDateFormatterLongStyle = CFDateFormatterStyle.longStyle
internal let kCFDateFormatterFullStyle = CFDateFormatterStyle.fullStyle
public var NSTimeIntervalSince1970: Double {
return 978307200.0
}
#if os(Windows)
extension TimeInterval {
init(_ ftTime: FILETIME) {
self = Double((ftTime.dwHighDateTime << 32) | ftTime.dwLowDateTime) - NSTimeIntervalSince1970;
}
}
#else
extension timeval {
internal init(_timeIntervalSince1970: TimeInterval) {
let (integral, fractional) = modf(_timeIntervalSince1970)
self.init(tv_sec: time_t(integral), tv_usec: suseconds_t(1.0e6 * fractional))
}
}
#endif
open class NSDate : NSObject, NSCopying, NSSecureCoding, NSCoding, @unchecked Sendable {
typealias CFType = CFDate
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as Date:
return isEqual(to: other)
case let other as NSDate:
return isEqual(to: Date(timeIntervalSinceReferenceDate: other.timeIntervalSinceReferenceDate))
default:
return false
}
}
deinit {
_CFDeinit(self)
}
internal final var _cfObject: CFType {
return unsafeBitCast(self, to: CFType.self)
}
internal let _base = _CFInfo(typeID: CFDateGetTypeID())
internal let _timeIntervalSinceReferenceDate: TimeInterval
open var timeIntervalSinceReferenceDate: TimeInterval {
return _timeIntervalSinceReferenceDate
}
open class var timeIntervalSinceReferenceDate: TimeInterval {
return Date().timeIntervalSinceReferenceDate
}
public convenience override init() {
self.init(timeIntervalSinceReferenceDate: CFAbsoluteTimeGetCurrent())
}
public required init(timeIntervalSinceReferenceDate ti: TimeInterval) {
_timeIntervalSinceReferenceDate = ti
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let ti = aDecoder.decodeDouble(forKey: "NS.time")
self.init(timeIntervalSinceReferenceDate: ti)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool {
return true
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(_timeIntervalSinceReferenceDate, forKey: "NS.time")
}
/**
A string representation of the date object (read-only).
The representation is useful for debugging only.
There are a number of options to acquire a formatted string for a date
including: date formatters (see
[NSDateFormatter](//apple_ref/occ/cl/NSDateFormatter) and
[Data Formatting Guide](//apple_ref/doc/uid/10000029i)),
and the `NSDate` methods `descriptionWithLocale:`,
`dateWithCalendarFormat:timeZone:`, and
`descriptionWithCalendarFormat:timeZone:locale:`.
*/
open override var description: String {
let dateFormatterRef = CFDateFormatterCreate(kCFAllocatorSystemDefault, nil, kCFDateFormatterFullStyle, kCFDateFormatterFullStyle)
let timeZone = CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorSystemDefault, 0.0)
CFDateFormatterSetProperty(dateFormatterRef, kCFDateFormatterTimeZoneKey, timeZone)
CFDateFormatterSetFormat(dateFormatterRef, "uuuu-MM-dd HH:mm:ss '+0000'"._cfObject)
return CFDateFormatterCreateStringWithDate(kCFAllocatorSystemDefault, dateFormatterRef, _cfObject)._swiftObject
}
/**
Returns a string representation of the receiver using the given locale.
- Parameter locale: An `NSLocale` object.
If you pass `nil`, `NSDate` formats the date in the same way as the
`description` property.
- Returns: A string representation of the receiver, using the given locale,
or if the locale argument is `nil`, in the international format
`YYYY-MM-DD HH:MM:SS ±HHMM`, where `±HHMM` represents the time zone
offset in hours and minutes from UTC (for example,
"2001-03-24 10:45:32 +0600")
*/
open func description(with locale: Locale?) -> String {
guard let aLocale = locale else { return description }
let dateFormatterRef = CFDateFormatterCreate(kCFAllocatorSystemDefault, aLocale._cfObject, kCFDateFormatterFullStyle, kCFDateFormatterFullStyle)
CFDateFormatterSetProperty(dateFormatterRef, kCFDateFormatterTimeZoneKey, CFTimeZoneCopySystem())
return CFDateFormatterCreateStringWithDate(kCFAllocatorSystemDefault, dateFormatterRef, _cfObject)._swiftObject
}
internal override var _cfTypeID: CFTypeID {
return CFDateGetTypeID()
}
}
extension NSDate {
public func timeIntervalSince(_ anotherDate: Date) -> TimeInterval {
return self.timeIntervalSinceReferenceDate - anotherDate.timeIntervalSinceReferenceDate
}
public var timeIntervalSinceNow: TimeInterval {
return timeIntervalSince(Date())
}
public var timeIntervalSince1970: TimeInterval {
return timeIntervalSinceReferenceDate + NSTimeIntervalSince1970
}
public func addingTimeInterval(_ ti: TimeInterval) -> Date {
return Date(timeIntervalSinceReferenceDate:_timeIntervalSinceReferenceDate + ti)
}
public func earlierDate(_ anotherDate: Date) -> Date {
if self.timeIntervalSinceReferenceDate < anotherDate.timeIntervalSinceReferenceDate {
return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate)
} else {
return anotherDate
}
}
public func laterDate(_ anotherDate: Date) -> Date {
if self.timeIntervalSinceReferenceDate < anotherDate.timeIntervalSinceReferenceDate {
return anotherDate
} else {
return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate)
}
}
public func compare(_ other: Date) -> ComparisonResult {
let t1 = self.timeIntervalSinceReferenceDate
let t2 = other.timeIntervalSinceReferenceDate
if t1 < t2 {
return .orderedAscending
} else if t1 > t2 {
return .orderedDescending
} else {
return .orderedSame
}
}
public func isEqual(to otherDate: Date) -> Bool {
return timeIntervalSinceReferenceDate == otherDate.timeIntervalSinceReferenceDate
}
}
extension NSDate {
internal static let _distantFuture = Date(timeIntervalSinceReferenceDate: 63113904000.0)
public class var distantFuture: Date {
return _distantFuture
}
internal static let _distantPast = Date(timeIntervalSinceReferenceDate: -63113904000.0)
public class var distantPast: Date {
return _distantPast
}
public convenience init(timeIntervalSinceNow secs: TimeInterval) {
self.init(timeIntervalSinceReferenceDate: secs + Date().timeIntervalSinceReferenceDate)
}
public convenience init(timeIntervalSince1970 secs: TimeInterval) {
self.init(timeIntervalSinceReferenceDate: secs - NSTimeIntervalSince1970)
}
public convenience init(timeInterval secsToBeAdded: TimeInterval, since date: Date) {
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate + secsToBeAdded)
}
}
extension Date : CustomPlaygroundDisplayConvertible {
public var playgroundDescription: Any {
let df = DateFormatter()
df.dateStyle = .medium
df.timeStyle = .short
return df.string(from: self)
}
}
open class NSDateInterval : NSObject, NSCopying, NSSecureCoding, @unchecked Sendable {
/*
NSDateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. NSDateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.
*/
public let startDate: Date
open var endDate: Date {
get {
if duration == 0 {
return startDate
} else {
return startDate + duration
}
}
}
public let duration: TimeInterval
// This method initializes an NSDateInterval object with start and end dates set to the current date and the duration set to 0.
public convenience override init() {
self.init(start: Date(), duration: 0)
}
public required convenience init?(coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
guard let start = coder.decodeObject(of: NSDate.self, forKey: "NS.startDate") else {
coder.failWithError(NSError(domain: NSCocoaErrorDomain, code: CocoaError.coderValueNotFound.rawValue, userInfo: nil))
return nil
}
guard let end = coder.decodeObject(of: NSDate.self, forKey: "NS.startDate") else {
coder.failWithError(NSError(domain: NSCocoaErrorDomain, code: CocoaError.coderValueNotFound.rawValue, userInfo: nil))
return nil
}
self.init(start: start._swiftObject, end: end._swiftObject)
}
// This method will throw an exception if the duration is less than 0.
public init(start startDate: Date, duration: TimeInterval) {
self.startDate = startDate
self.duration = duration
}
// This method will throw an exception if the end date comes before the start date.
public convenience init(start startDate: Date, end endDate: Date) {
self.init(start: startDate, duration: endDate.timeIntervalSince(startDate))
}
open func copy(with zone: NSZone?) -> Any {
return NSDateInterval(start: startDate, duration: duration)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(startDate._nsObject, forKey: "NS.startDate")
aCoder.encode(endDate._nsObject, forKey: "NS.endDate")
}
public static var supportsSecureCoding: Bool {
return true
}
/*
(ComparisonResult)compare:(NSDateInterval *) prioritizes ordering by start date. If the start dates are equal, then it will order by duration.
e.g.
Given intervals a and b
a. |-----|
b. |-----|
[a compare:b] would return NSOrderAscending because a's startDate is earlier in time than b's start date.
In the event that the start dates are equal, the compare method will attempt to order by duration.
e.g.
Given intervals c and d
c. |-----|
d. |---|
[c compare:d] would result in NSOrderDescending because c is longer than d.
If both the start dates and the durations are equal, then the intervals are considered equal and NSOrderedSame is returned as the result.
*/
open func compare(_ dateInterval: DateInterval) -> ComparisonResult {
let result = startDate.compare(dateInterval.start)
if result == .orderedSame {
if self.duration < dateInterval.duration { return .orderedAscending }
if self.duration > dateInterval.duration { return .orderedDescending }
return .orderedSame
}
return result
}
open func isEqual(to dateInterval: DateInterval) -> Bool {
return startDate == dateInterval.start && duration == dateInterval.duration
}
open func intersects(_ dateInterval: DateInterval) -> Bool {
return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(startDate) || dateInterval.contains(endDate)
}
/*
This method returns an NSDateInterval object that represents the interval where the given date interval and the current instance intersect. In the event that there is no intersection, the method returns nil.
*/
open func intersection(with dateInterval: DateInterval) -> DateInterval? {
if !intersects(dateInterval) {
return nil
}
if isEqual(to: dateInterval) {
return DateInterval(start: startDate, duration: duration)
}
let timeIntervalForSelfStart = startDate.timeIntervalSinceReferenceDate
let timeIntervalForSelfEnd = startDate.timeIntervalSinceReferenceDate
let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate
let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate
let resultStartDate : Date
if timeIntervalForGivenStart >= timeIntervalForSelfStart {
resultStartDate = dateInterval.start
} else {
// self starts after given
resultStartDate = startDate
}
let resultEndDate : Date
if timeIntervalForGivenEnd >= timeIntervalForSelfEnd {
resultEndDate = endDate
} else {
// given ends before self
resultEndDate = dateInterval.end
}
return DateInterval(start: resultStartDate, end: resultEndDate)
}
open func contains(_ date: Date) -> Bool {
let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate
let timeIntervalForSelfStart = startDate.timeIntervalSinceReferenceDate
let timeIntervalforSelfEnd = endDate.timeIntervalSinceReferenceDate
if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) {
return true
}
return false
}
}
// MARK: - Bridging
extension NSDate : _StructTypeBridgeable {
public typealias _StructType = Date
public func _bridgeToSwift() -> Date {
return Date._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSDateInterval : _StructTypeBridgeable {
public typealias _StructType = DateInterval
public func _bridgeToSwift() -> DateInterval {
return DateInterval._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSDateInterval : _SwiftBridgeable {
var _swiftObject: DateInterval {
return _bridgeToSwift()
}
}
extension NSDate: _SwiftBridgeable {
typealias SwiftType = Date
var _swiftObject: Date {
return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate)
}
}
extension CFDate : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSDate
typealias SwiftType = Date
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
internal var _swiftObject: Date { return _nsObject._swiftObject }
}
extension Date : _NSBridgeable {
typealias NSType = NSDate
typealias CFType = CFDate
internal var _nsObject: NSType { return NSDate(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
extension Date : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDate {
return NSDate(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate)
}
public static func _forceBridgeFromObjectiveC(_ x: NSDate, result: inout Date?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(NSDate.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSDate, result: inout Date?) -> Bool {
result = Date(timeIntervalSinceReferenceDate: x.timeIntervalSinceReferenceDate)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDate?) -> Date {
var result: Date? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}