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
有帮助吗?

解决方案

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"]]; 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top