检查指定的日期是今天,昨天还是将来的日期

时间:2011-10-12 07:03:50

标签: iphone objective-c nsdate

我有一个关于NSDate的查询。我有一个日期,即“2011-10-04 07:36:38 +0000”,我想检查这个日期是昨天,今天还是将来的日期。

我该怎么做?

4 个答案:

答案 0 :(得分:44)

试试这个:

注意:根据需要更改日期格式。

NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/yyyy"];
NSDate* enteredDate = [df dateFromString:@"10/04/2011"];
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:enteredDate];
switch (result)
{
    case NSOrderedAscending: 
        NSLog(@"Future Date");
                    break;
    case NSOrderedDescending: 
        NSLog(@"Earlier Date");
                    break;
    case NSOrderedSame: 
        NSLog(@"Today/Null Date Passed"); //Not sure why This is case when null/wrong date is passed
                    break;
}

答案 1 :(得分:7)

请参阅Apple's documentation on date calculations

NSDate *startDate = ...;
NSDate *endDate = ...;

NSCalendar *gregorian = [[NSCalendar alloc]
                 initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                          fromDate:startDate
                                          toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];

如果days介于+1和-1之间,则您的日期是“今天”的候选人。显然你需要考虑如何处理时间。据推测,最简单的方法是将所有日期设置为相关日期的00:00.00小时(truncate the date using an approach like this),然后使用这些值进行计算。这样你今天得0,昨天得-1,明天+1,任何其他价值也会告诉你未来或过去的情况。

答案 2 :(得分:2)

根据您的需要使用以下任何一项,

– earlierDate:
– laterDate:
– compare:

请参阅此http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

答案 3 :(得分:1)

-(NSString*)timeAgoFor:(NSString*)tipping_date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:tipping_date];
    NSString *key = @"";
    NSTimeInterval ti = [date timeIntervalSinceDate:[NSDate date]];
    key = (ti > 0) ? @"Left" : @"Ago";

    ti = ABS(ti);
    NSDate * today = [NSDate date];
    NSComparisonResult result = [today compare:date];

    if (result == NSOrderedSame) {
        return[NSString stringWithFormat:@"Today"];
    }
    else if (ti < 86400 * 2) {
        return[NSString stringWithFormat:@"1 Day %@",key];
    }else if (ti < 86400 * 7) {
        int diff = round(ti / 60 / 60 / 24);
        return[NSString stringWithFormat:@"%d Days %@", diff,key];
    }else {
        int diff = round(ti / (86400 * 7));
        return[NSString stringWithFormat:@"%d Wks %@", diff,key];
    }
}