iOS 时间转化成前天、昨天、今天

有时候我们需要根据项目的需求,把最近三天的时间变成前天加时间、昨天加时间、今天加时间;

代码如下:

//时间和当前时间比较
+ (NSString *)backgroundTimeIsEqualCurrentDate{
    NSString *str = @"2017-06-25 17:00"
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];//设置时间格式
    NSDate *date = [dateFormatter dateFromString:dateStr];
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today = [[NSDate alloc] init];
    NSDate *tomorrow, *yesterday;
    tomorrow = [today dateByAddingTimeInterval: -secondsPerDay*2];//前天
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];//昨天
    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * tomorrowString = [[tomorrow description] substringToIndex:10];
    
    NSString * dateString = [[date description] substringToIndex:10];
//[date description]返回的是时间,比当前时间少八个小时,这并不影响时间的判断
    NSString *hourAndMin = [dateStr substringWithRange:NSMakeRange(11, 5)];
    if ([dateString isEqualToString:todayString]) {
        return [NSString stringWithFormat:@"今天 %@", hourAndMin];
    } else if ([dateString isEqualToString:yesterdayString]) {
        return [NSString stringWithFormat:@"昨天 %@", hourAndMin];
    }else if ([dateString isEqualToString:tomorrowString])
    {
        return [NSString stringWithFormat:@"前天 %@", hourAndMin];
    }
    else {
        return dateStr;
    }
}

这样就可以把最近三天的时间变成前天昨天今天的样式啦!

你可能感兴趣的:(iOS 时间转化成前天、昨天、今天)