Differences in NSDateComponents syntax?

Swift 2

The NSCalendarUnit names have changed in Swift 2.

Also, now we have to pass these arguments in an OptionSet, like this:

let components = calendar.components([.Hour, .Minute, .Second, .Nanosecond], fromDate: date)

Swift 3

Many things have changed, according to the Swift API Design Guidelines.

Updated syntax:

let date = Date()
let calendar = Calendar.current()
let components = calendar.components([.hour, .minute, .second, .nanosecond], from: date)

Swift 4

Calendar.current is now a property, and .components has been renamed to .dateComponents. Otherwise it’s the same as in Swift 3.

let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute, .second, .nanosecond], from: date)

Leave a Comment