开发者

NSDateComponents giving wrong day for 28 Feb

开发者 https://www.devze.com 2023-02-21 05:02 出处:网络
I\'m attempting to do a search within February. So I want to figure out if the last day is 28 or 29. I\'m doing a subtraction from the end of Mar开发者_C百科ch

I'm attempting to do a search within February. So I want to figure out if the last day is 28 or 29. I'm doing a subtraction from the end of Mar开发者_C百科ch

NSDate* endFeb = [march dateByAddingTimeInterval: (NSTimeInterval) -24 * 3600];
NSDateComponents *feb = [gregorian components: units fromDate: endFeb];

which gives me the correct date but not the right day

(gdb) po [gregorian dateFromComponents: feb]
2011-02-28 00:00:00 +0000
(gdb) p (int) [feb day]
$1 = 27

This is on the iPad 4.3 simulator if it matters.


To figure out if february has 28 or 29 days you would use something like this:

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2008];
[components setMonth:2];
[components setDay:1];
NSDate *febDate = [calendar dateFromComponents:components];

NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:febDate];

NSLog(@"%u days in february", range.length);

This way you don't have to mess with timezone offsets. I guess this is the problem with your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消