Question

I get year 2012 from dateFromComponents and my current date is 2013. Why is that? I haven't change the year anywhere.

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSCalendarUnitYear fromDate:[NSDate date]];

NSLog(@"%ld", (long)[comp year]); //2013

NSLog(@"%@", [cal dateFromComponents:comp]); // 2012-12-31 23:00:00 +0000
Was it helpful?

Solution

Your conversion takes the time zone from the calendar into account, which you probably don't want in this case when just splitting a date into components. Set the time zone to GMT and it should give you the result you want;

[cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top