今天项目遇到个需求,需要根据时间来显示不同的样式,于是去翻了一下NSCalendar,发现苹果其实是提供了这个API的

1
2
3
4
5
6
7
8
/*
This API reports if the date is within "today".
*/

- (BOOL)isDateInToday:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
/*
This API reports if the date is within "yesterday".
*/

- (BOOL)isDateInYesterday:(NSDate *)date NS_AVAILABLE(10_9, 8_0);

可是我们项目需要兼容到iOS7,没办法只能自己动手了因为懒,最后还是google了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
+(BOOL)isInToday:(NSDate *)date
{
if([[NSCalendar currentCalendar] respondsToSelector:@selector(isDateInToday:)]) //iOS8以上直接使用系统api
{
return [[NSCalendar currentCalendar] isDateInToday:date];
}
else
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit calendarUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;

NSDateComponents *components = [calendar components:calendarUnits
fromDate:date];
NSDateComponents *todayComponents = [calendar components:calendarUnits
fromDate:[NSDate date]];

NSDate *lessGranularDate1 = [calendar dateFromComponents:components];
NSDate *lessGranularToday = [calendar dateFromComponents:todayComponents];

BOOL isInToday = [lessGranularDate1 isEqualToDate:lessGranularToday];

return isInToday;
}
}
+(BOOL)isInYesterDay:(NSDate *)date
{
if([[NSCalendar currentCalendar] respondsToSelector:@selector(isDateInYesterday:)])//iOS8以上直接使用系统api
{
return [[NSCalendar currentCalendar] isDateInYesterday:date];
}
else
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit calendarUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;

NSDateComponents *components = [calendar components:calendarUnits
fromDate:date];
NSDateComponents *yesterdayComponents = [calendar components:calendarUnits
fromDate:[[NSDate date] dateByAddingTimeInterval:-1*60*60*24]];

NSDate *lessGranularDate1 = [calendar dateFromComponents:components];
NSDate *lessGranularYesterday = [calendar dateFromComponents:yesterdayComponents];

BOOL isYesterday = [lessGranularDate1 isEqualToDate:lessGranularYesterday];

return isYesterday;
}
}