The following will create an NSDateComponents
object containing day
and weekday
but not hour
:
var today = NSDate()
var gregorian = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var flags: NSCalendarUnit = .DayCalendarUnit | .WeekdayCalendarUnit
var components = gregorian.components(flags, fromDate: today)
// valid
components.day
components.weekday
// invalid
components.hour
In order to have hour
, I would have to |
-in the .HourCalendarUnit
like this:
flags = flags | .HourCalendarUnit
Is there a flag to specify all flags? Or do I just have to manually |
them all in if I want an NSDateComponents
to have them all?
Alternatively, and ideally, I would like to just be able to say today.hour
without using NSDateComponents
at all. Does such a class exist?
NSCalendarUnit
can be initialized with an UInt
, so this gives you
all possible components:
var today = NSDate()
var gregorian = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var flags = NSCalendarUnit(UInt.max)
var components = gregorian.components(flags, fromDate: today)
A today.hour
method does not exist because the calculation cannot be done without
knowing the time zone to use for the conversion.
Update for Swift 2:
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let flags = NSCalendarUnit(rawValue: UInt.max)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With