-2

I have an NSDate 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 reservationDate NSDate 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 = components.day
let hour = components.hour
Nirav D
  • 71,513
  • 12
  • 161
  • 183
AfterCoder
  • 731
  • 2
  • 6
  • 22

3 Answers3

1

Try to set timezone with Calendar object with UTC

let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(name: "UTC")!
let components = calendar.components(unitFlags, fromDate: NSDate())
let day = components.day
let hour = components.hour
Nirav D
  • 71,513
  • 12
  • 161
  • 183
1

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

NSCalendar.currentCalendar().timeZone = NSTimeZone(name: "UTC")!
Apurv
  • 17,116
  • 8
  • 51
  • 67
0
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
var convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy, HH:mm"
convertedDate = dateFormatter.stringFromDate(currentDate)
Dravidian
  • 9,945
  • 3
  • 34
  • 74