Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dateFromComponents gives Wrong date

I am trying to get a Date object from NSDateComponents, but Calendar.date(from: Components) is giving a date one day before the date that was in my original components.

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
like image 466
iPhone Guy Avatar asked Aug 29 '26 04:08

iPhone Guy


2 Answers

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

calendar.timeZone = NSTimeZone(name: "UTC")!
like image 125
Nirav D Avatar answered Aug 31 '26 21:08

Nirav D


It's giving you the UTC time zone, Just convert the Date by usning NSDateFormatter like this, you will get your answer -

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


let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd"
let datestring = df.stringFromDate(calendar!.dateFromComponents(dateComponents)!)
print(datestring)

enter image description here

like image 37
Anupam Mishra Avatar answered Aug 31 '26 22:08

Anupam Mishra