时间字符串距离现在天数时间月份

第一:NSDate,可以直接存储,然后拿出来使用!

NSDate *adate = [NSDate date];

[[NSUserDefaults standardUserDefaults] setObject:adate forKey:@"CurrentDate"];

第二:时间字符串转为 NSDate

NSDateFormatter *format=[[NSDateFormatter alloc] init];

[format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *fromdate=[format dateFromString:@"2017-02-01 9:31:27"];

第三:开始比较

// 1.获得年月日

NSCalendar *calendar = [NSCalendar currentCalendar];

NSUInteger unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute;

NSDateComponents *cmp1 = [calendar components:unitFlags fromDate:fromdate];

NSDateComponents *cmp2 = [calendar components:unitFlags fromDate:d];

// 2.格式化日期

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

if ([cmp1 day] == [cmp2 day]) { // 今天

formatter.dateFormat = @"今天 HH:mm";

}

else if ([cmp2 year] == [cmp2 year]) { // 今年

formatter.dateFormat = @"MM-dd HH:mm";

} else {

formatter.dateFormat = @"yyyy-MM-dd HH:mm";

}

NSString *time = [formatter stringFromDate:d];

推荐阅读更多精彩内容