iPhone Guy iPhone Guy - 4 months ago 27
iOS Question

dateFromComponents gives Wrong date

I am trying to get the date that i am set in

NSDateComponents
, but it returing the one day less than the actual date.

let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = calendar!.components([.Year , .Month , .Weekday, .Day], fromDate: NSDate())
dateComponents.year = 2015
dateComponents.month = 9
dateComponents.day = 1





po calendar!.dateFromComponents(dateComponents)
▿ Optional(2015-08-31 18:30:00 +0000)
- Some : 2015-08-31 18:30:00 +0000

Answer

Set the time zone with calendar object to UTC, and the try to get Date from the calendar.

calendar.timeZone = NSTimeZone(name: "UTC")!