Why does NSCalendar dateFromComponents return an invalid date?

I expect 2010-10-11 00:00:00

But instead, I get 2010-10-10 21:00:00 +0000

I know that I can add a few hours and get the desired date, but I don’t understand why I get the previous day with 21 hours ...

Please, help!

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2010];
[comps setMonth:10];
[comps setDay:11];

[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *retDate = [cal dateFromComponents:comps];
+5
source share
2 answers

I think your problem can be solved by installation NSTimeZone.

+15
source

If you need a specific time format, use this formatter, otherwise write it to get the correct time. first option...

let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let localDate = formatter.dateFromString("1989-10-17T05:00:00.000-0000")

or if you need a date from the components, use the code below, for example ...

let calendar = NSCalendar.currentCalendar()
    calendar.timeZone = NSTimeZone(name: "GMT")!
    let date = calendar.dateFromComponents(components)

0

All Articles