Compare NSDate for Today or Yesterday

前端 未结 4 1306
-上瘾入骨i
-上瘾入骨i 2020-12-30 10:03

Well I guess this has been asked a thousand times, but for some reason the answeres dont really work or had other problems,....

Anyway here is what I have \"working\

4条回答
  •  粉色の甜心
    2020-12-30 10:51

    The easiest way to do it is to just compare the description of the dates:

    // Your dates:
    NSDate * today = [NSDate date];
    NSDate * yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400]; //86400 is the seconds in a day
    NSDate * refDate; // your reference date
    
    // 10 first characters of description is the calendar date:
    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * refDateString = [[refDate description] substringToIndex:10];
    
    if ([refDateString isEqualToString:todayString]) 
    {
        cell.title.text =  @"Today";
    } else if ([refDateString isEqualToString:yesterdayString]) 
    {
        cell.title.text =  @"Yesterday";
    } else 
    {
        cell.title.text =  refDateString;
    }
    

    If you want to change the format of the date string you could use descriptionWithLocale: instead.

提交回复
热议问题