检查日期是否在同一日历日

时间:2009-06-09 05:37:06

标签: iphone objective-c calendar

有人可以帮我弄清楚如何检查某个日期是否与今天同一天。我想这需要在同一时区的同一天的0小时创建一个日历日并检查,但到目前为止,我的尝试让我更加困惑。

2 个答案:

答案 0 :(得分:5)

NSCalendar让您处理人类的日子。所以你可以实现这样的类别:

@implementation NSDate (IsItToday)
- (BOOL)isToday {
    NSUInteger desiredComponents = NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSDateComponents *myCalendarDate = [[NSCalendar currentCalendar] components:desiredComponents fromDate:self];
    NSDateComponents *today = [[NSCalendar currentCalendar] components:desiredComponents fromDate:[NSDate date]];
    return [myCalendarDate isEqual:today];
}
@end

答案 1 :(得分:-1)

你应该仔细阅读这个Dates and Times Programming Topics for Cocoa,但这样的事情应该有效:

NSDate *today = [NSDate date];
NSTimeInterval difference = [today timeIntervalSinceDate:otherDate];
NSTimeInterval secondsPerDay = 24 * 60 * 60;
if (difference < secondsPerDay)
{
   //same day as today
}