- Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathDateComponents.swift
465 lines (410 loc) · 20.1 KB
/
DateComponents.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
//===----------------------------------------------------------------------===//
import CoreFoundation
/**
`DateComponents` encapsulates the components of a date in an extendable, structured manner.
It is used to specify a date by providing the temporal components that make up a date and time in a particular calendar: hour, minutes, seconds, day, month, year, and so on. It can also be used to specify a duration of time, for example, 5 hours and 16 minutes. A `DateComponents` is not required to define all the component fields.
When a new instance of `DateComponents` is created, the date components are set to `nil`.
*/
publicstructDateComponents:ReferenceConvertible,Hashable,Equatable,_MutableBoxing{
publictypealiasReferenceType=NSDateComponents
internalvar_handle:_MutableHandle<NSDateComponents>
/// Initialize a `DateComponents`, optionally specifying values for its fields.
publicinit(calendar:Calendar?=nil,
timeZone:TimeZone?=nil,
era:Int?=nil,
year:Int?=nil,
month:Int?=nil,
day:Int?=nil,
hour:Int?=nil,
minute:Int?=nil,
second:Int?=nil,
nanosecond:Int?=nil,
weekday:Int?=nil,
weekdayOrdinal:Int?=nil,
quarter:Int?=nil,
weekOfMonth:Int?=nil,
weekOfYear:Int?=nil,
yearForWeekOfYear:Int?=nil){
_handle =_MutableHandle(adoptingReference:NSDateComponents())
iflet _calendar = calendar {self.calendar = _calendar }
iflet _timeZone = timeZone {self.timeZone = _timeZone }
iflet _era = era {self.era = _era }
iflet _year = year {self.year = _year }
iflet _month = month {self.month = _month }
iflet _day = day {self.day = _day }
iflet _hour = hour {self.hour = _hour }
iflet _minute = minute {self.minute = _minute }
iflet _second = second {self.second = _second }
iflet _nanosecond = nanosecond {self.nanosecond = _nanosecond }
iflet _weekday = weekday {self.weekday = _weekday }
iflet _weekdayOrdinal = weekdayOrdinal {self.weekdayOrdinal = _weekdayOrdinal }
iflet _quarter = quarter {self.quarter = _quarter }
iflet _weekOfMonth = weekOfMonth {self.weekOfMonth = _weekOfMonth }
iflet _weekOfYear = weekOfYear {self.weekOfYear = _weekOfYear }
iflet _yearForWeekOfYear = yearForWeekOfYear {self.yearForWeekOfYear = _yearForWeekOfYear }
}
// MARK: - Properties
/// Translate from the NSDateComponentUndefined value into a proper Swift optional
privatefunc _getter(_ x :Int)->Int?{return x == NSDateComponentUndefined ?nil: x }
/// Translate from the proper Swift optional value into an NSDateComponentUndefined
privatefunc _setter(_ x :Int?)->Int{iflet xx = x {return xx }else{return NSDateComponentUndefined }}
/// The `Calendar` used to interpret the other values in this structure.
///
/// - note: API which uses `DateComponents` may have different behavior if this value is `nil`. For example, assuming the current calendar or ignoring certain values.
publicvarcalendar:Calendar?{
get{return _handle.map{ $0.calendar }}
set{_applyMutation{ $0.calendar = newValue }}
}
/// A time zone.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvartimeZone:TimeZone?{
get{return _handle.map{ $0.timeZone }}
set{_applyMutation{ $0.timeZone = newValue }}
}
/// An era or count of eras.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarera:Int?{
get{return _handle.map{_getter($0.era)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.era = value }
}
}
/// A year or count of years.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvaryear:Int?{
get{return _handle.map{_getter($0.year)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.year = value }
}
}
/// A month or count of months.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarmonth:Int?{
get{return _handle.map{_getter($0.month)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.month = value }
}
}
/// A day or count of days.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarday:Int?{
get{return _handle.map{_getter($0.day)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.day = value }
}
}
/// An hour or count of hours.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarhour:Int?{
get{return _handle.map{_getter($0.hour)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.hour = value }
}
}
/// A minute or count of minutes.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarminute:Int?{
get{return _handle.map{_getter($0.minute)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.minute = value }
}
}
/// A second or count of seconds.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarsecond:Int?{
get{return _handle.map{_getter($0.second)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.second = value }
}
}
/// A nanosecond or count of nanoseconds.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarnanosecond:Int?{
get{return _handle.map{_getter($0.nanosecond)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.nanosecond = value }
}
}
/// A weekday or count of weekdays.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarweekday:Int?{
get{return _handle.map{_getter($0.weekday)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.weekday = value }
}
}
/// A weekday ordinal or count of weekday ordinals.
/// Weekday ordinal units represent the position of the weekday within the next larger calendar unit, such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month.///
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarweekdayOrdinal:Int?{
get{return _handle.map{_getter($0.weekdayOrdinal)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.weekdayOrdinal = value }
}
}
/// A quarter or count of quarters.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarquarter:Int?{
get{return _handle.map{_getter($0.quarter)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.quarter = value }
}
}
/// A week of the month or a count of weeks of the month.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarweekOfMonth:Int?{
get{return _handle.map{_getter($0.weekOfMonth)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.weekOfMonth = value }
}
}
/// A week of the year or count of the weeks of the year.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvarweekOfYear:Int?{
get{return _handle.map{_getter($0.weekOfYear)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.weekOfYear = value }
}
}
/// The ISO 8601 week-numbering year of the receiver.
///
/// The Gregorian calendar defines a week to have 7 days, and a year to have 356 days, or 366 in a leap year. However, neither 356 or 366 divide evenly into a 7 day week, so it is often the case that the last week of a year ends on a day in the next year, and the first week of a year begins in the preceding year. To reconcile this, ISO 8601 defines a week-numbering year, consisting of either 52 or 53 full weeks (364 or 371 days), such that the first week of a year is designated to be the week containing the first Thursday of the year.
///
/// You can use the yearForWeekOfYear property with the weekOfYear and weekday properties to get the date corresponding to a particular weekday of a given week of a year. For example, the 6th day of the 53rd week of the year 2005 (ISO 2005-W53-6) corresponds to Sat 1 January 2005 on the Gregorian calendar.
/// - note: This value is interpreted in the context of the calendar in which it is used.
publicvaryearForWeekOfYear:Int?{
get{return _handle.map{_getter($0.yearForWeekOfYear)}}
set{
letvalue=_setter(newValue)
_applyMutation{ $0.yearForWeekOfYear = value }
}
}
/// Set to true if these components represent a leap month.
publicvarisLeapMonth:Bool?{
get{return _handle.map{ $0.leapMonthSet ? $0.isLeapMonth :nil}}
set{
_applyMutation{
// Technically, the underlying class does not support setting isLeapMonth to nil, but it could - so we leave the API consistent.
iflet b = newValue {
$0.isLeapMonth = b
}else{
$0.isLeapMonth =false
}
}
}
}
/// Returns a `Date` calculated from the current components using the `calendar` property.
publicvardate:Date?{
iflet d = _handle.map({$0.date}){
return d asDate
}else{
returnnil
}
}
// MARK: - Generic Setter/Getters
/// Set the value of one of the properties, using an enumeration value instead of a property name.
///
/// The calendar and timeZone and isLeapMonth properties cannot be set by this method.
publicmutatingfunc setValue(_ value:Int?, for component:Calendar.Component){
let_value=_setter(value)
_applyMutation{
$0.setValue(_value, forComponent:Calendar._toCalendarUnit([component]))
}
}
/// Returns the value of one of the properties, using an enumeration value instead of a property name.
///
/// The calendar and timeZone and isLeapMonth property values cannot be retrieved by this method.
publicfunc value(for component:Calendar.Component)->Int?{
return _handle.map{
$0.value(forComponent:Calendar._toCalendarUnit([component]))
}
}
// MARK: -
/// Returns true if the combination of properties which have been set in the receiver is a date which exists in the `calendar` property.
///
/// This method is not appropriate for use on `DateComponents` values which are specifying relative quantities of calendar components.
///
/// Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap.
///
/// If the time zone property is set in the `DateComponents`, it is used.
///
/// The calendar property must be set, or the result is always `false`.
publicvarisValidDate:Bool{
return _handle.map{ $0.isValidDate }
}
/// Returns true if the combination of properties which have been set in the receiver is a date which exists in the specified `Calendar`.
///
/// This method is not appropriate for use on `DateComponents` values which are specifying relative quantities of calendar components.
///
/// Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap.
///
/// If the time zone property is set in the `DateComponents`, it is used.
publicfunc isValidDate(in calendar:Calendar)->Bool{
return _handle.map{ $0.isValidDate(in: calendar)}
}
// MARK: -
publicvarhashValue:Int{
return _handle.map{ $0.hash }
}
publicstaticfunc==(lhs:DateComponents, rhs:DateComponents)->Bool{
// Don't copy references here; no one should be storing anything
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
// MARK: - Bridging Helpers
internalinit(reference:NSDateComponents){
_handle =_MutableHandle(reference: reference)
}
}
extensionDateComponents:CustomStringConvertible,CustomDebugStringConvertible,CustomReflectable{
publicvardescription:String{
return _handle.map{ $0.description }
}
publicvardebugDescription:String{
return _handle.map{ $0.debugDescription }
}
publicvarcustomMirror:Mirror{
varc:[(label:String?, value:Any)]=[]
iflet r = calendar { c.append((label:"calendar", value: r))}
iflet r = timeZone { c.append((label:"timeZone", value: r))}
iflet r = era { c.append((label:"era", value: r))}
iflet r = year { c.append((label:"year", value: r))}
iflet r = month { c.append((label:"month", value: r))}
iflet r = day { c.append((label:"day", value: r))}
iflet r = hour { c.append((label:"hour", value: r))}
iflet r = minute { c.append((label:"minute", value: r))}
iflet r = second { c.append((label:"second", value: r))}
iflet r = nanosecond { c.append((label:"nanosecond", value: r))}
iflet r = weekday { c.append((label:"weekday", value: r))}
iflet r = weekdayOrdinal { c.append((label:"weekdayOrdinal", value: r))}
iflet r = quarter { c.append((label:"quarter", value: r))}
iflet r = weekOfMonth { c.append((label:"weekOfMonth", value: r))}
iflet r = weekOfYear { c.append((label:"weekOfYear", value: r))}
iflet r = yearForWeekOfYear { c.append((label:"yearForWeekOfYear", value: r))}
iflet r = isLeapMonth { c.append((label:"isLeapMonth", value: r))}
returnMirror(self, children: c, displayStyle:Mirror.DisplayStyle.struct)
}
}
// MARK: - Bridging
extensionDateComponents:_ObjectiveCBridgeable{
publicstaticfunc _isBridgedToObjectiveC()->Bool{
returntrue
}
publicstaticfunc _getObjectiveCType()->Any.Type{
returnNSDateComponents.self
}
@_semantics("convertToObjectiveC")
publicfunc _bridgeToObjectiveC()->NSDateComponents{
return _handle._copiedReference()
}
publicstaticfunc _forceBridgeFromObjectiveC(_ dateComponents:NSDateComponents, result:inoutDateComponents?){
if !_conditionallyBridgeFromObjectiveC(dateComponents, result:&result){
fatalError("Unable to bridge \(DateComponents.self) to \(self)")
}
}
publicstaticfunc _conditionallyBridgeFromObjectiveC(_ dateComponents:NSDateComponents, result:inoutDateComponents?)->Bool{
result =DateComponents(reference: dateComponents)
returntrue
}
publicstaticfunc _unconditionallyBridgeFromObjectiveC(_ source:NSDateComponents?)->DateComponents{
varresult:DateComponents?=nil
_forceBridgeFromObjectiveC(source!, result:&result)
return result!
}
}
extensionDateComponents:Codable{
privateenumCodingKeys:Int,CodingKey{
case calendar
case timeZone
case era
case year
case month
case day
case hour
case minute
case second
case nanosecond
case weekday
case weekdayOrdinal
case quarter
case weekOfMonth
case weekOfYear
case yearForWeekOfYear
}
publicinit(from decoder:Decoder)throws{
letcontainer=try decoder.container(keyedBy:CodingKeys.self)
letcalendar=try container.decodeIfPresent(Calendar.self, forKey:.calendar)
lettimeZone=try container.decodeIfPresent(TimeZone.self, forKey:.timeZone)
letera=try container.decodeIfPresent(Int.self, forKey:.era)
letyear=try container.decodeIfPresent(Int.self, forKey:.year)
letmonth=try container.decodeIfPresent(Int.self, forKey:.month)
letday=try container.decodeIfPresent(Int.self, forKey:.day)
lethour=try container.decodeIfPresent(Int.self, forKey:.hour)
letminute=try container.decodeIfPresent(Int.self, forKey:.minute)
letsecond=try container.decodeIfPresent(Int.self, forKey:.second)
letnanosecond=try container.decodeIfPresent(Int.self, forKey:.nanosecond)
letweekday=try container.decodeIfPresent(Int.self, forKey:.weekday)
letweekdayOrdinal=try container.decodeIfPresent(Int.self, forKey:.weekdayOrdinal)
letquarter=try container.decodeIfPresent(Int.self, forKey:.quarter)
letweekOfMonth=try container.decodeIfPresent(Int.self, forKey:.weekOfMonth)
letweekOfYear=try container.decodeIfPresent(Int.self, forKey:.weekOfYear)
letyearForWeekOfYear=try container.decodeIfPresent(Int.self, forKey:.yearForWeekOfYear)
self.init(calendar: calendar,
timeZone: timeZone,
era: era,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
nanosecond: nanosecond,
weekday: weekday,
weekdayOrdinal: weekdayOrdinal,
quarter: quarter,
weekOfMonth: weekOfMonth,
weekOfYear: weekOfYear,
yearForWeekOfYear: yearForWeekOfYear)
}
publicfunc encode(to encoder:Encoder)throws{
varcontainer= encoder.container(keyedBy:CodingKeys.self)
try container.encodeIfPresent(self.calendar, forKey:.calendar)
try container.encodeIfPresent(self.timeZone, forKey:.timeZone)
try container.encodeIfPresent(self.era, forKey:.era)
try container.encodeIfPresent(self.year, forKey:.year)
try container.encodeIfPresent(self.month, forKey:.month)
try container.encodeIfPresent(self.day, forKey:.day)
try container.encodeIfPresent(self.hour, forKey:.hour)
try container.encodeIfPresent(self.minute, forKey:.minute)
try container.encodeIfPresent(self.second, forKey:.second)
try container.encodeIfPresent(self.nanosecond, forKey:.nanosecond)
try container.encodeIfPresent(self.weekday, forKey:.weekday)
try container.encodeIfPresent(self.weekdayOrdinal, forKey:.weekdayOrdinal)
try container.encodeIfPresent(self.quarter, forKey:.quarter)
try container.encodeIfPresent(self.weekOfMonth, forKey:.weekOfMonth)
try container.encodeIfPresent(self.weekOfYear, forKey:.weekOfYear)
try container.encodeIfPresent(self.yearForWeekOfYear, forKey:.yearForWeekOfYear)
}
}