2011-10-12 107 views

回答

42

试试这个:

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

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; 
} 
+5

每个案例陈述后应该有一个中断,以免在其他案件中输入。 –

+0

请注意,这将永远不会返回“今天” - NSDate代表一个特定的时间即时,所以'NSOrderedSame'将(实质上)永远不会发生 – Tim

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时(truncate the date using an approach like this),然后使用这些值进行计算。这样你今天得到0,昨天得到-1,明天得+1,而其他任何价值都会告诉你未来或过去有多远。

+0

这会起作用,但为避免夏时制变化出现错误,将小时设置为中午(12:00:00)会更安全。 – Suz

+0

具有讽刺意味的是,我原来建议将时间设置为中午,但截断的例子已将其设置为午夜,我认为可以保持一致!但是,如果两个日期都在同一个时区,那么这将不会产生任何影响,因为夏令时会在凌晨2点发生变化,并将时钟恢复为凌晨1点,因此在所有情况下,来自同一时区的两个日期将截断为相同的日历日期,无论夏时制如何。 –

+0

如果您实际上想要考虑时区,最好的方法是在做其他任何事情之前将这两个日期转换为同一时区。 –

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]; 
    } 
} 
+0

我用这个,但不知何故今天从来没有过,所以我不得不修改它,以便我只比较日期。休息工作正常。最后得到了它与它的时间比较的问题。我必须做相应的调整 – ChArAnJiT

相关问题