Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSCalendarUnit flag to set all flags

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?

like image 550
Chris Redford Avatar asked Aug 05 '14 23:08

Chris Redford


1 Answers

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)
like image 73
Martin R Avatar answered Nov 06 '22 19:11

Martin R