Atakan Atakan - 1 year ago 97
Swift Question

How to fetch day, month and hour from NSDate in Swift

I have an

object called reservationDate and I want to fetch day, month and hour from the Date. However, I'm getting wrong values. How can I get these values?

The value of the reservationDate object
2016-08-05 21:00:00 UTC

thus I expect to get 5 as a day and 21 as a hour however I'm receiving 6 as a day and 0 as a hour. Should I expect something else?

let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: reservationDate)
let day =
let hour = components.hour

Answer Source

You have not set Time zone. Please assign it "UTC".

NSCalendar.currentCalendar().timeZone = NSTimeZone(name: "UTC")!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download