-
Notifications
You must be signed in to change notification settings - Fork 41
/
NSDate+SafeCompare.m
60 lines (53 loc) · 1.37 KB
/
NSDate+SafeCompare.m
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
49
50
51
52
53
54
55
56
57
58
59
60
#define NSDateIsLaterThan NSOrderedDescending
#define NSDateIsEarlierThan NSOrderedAscending
@implementation NSDate (SafeCompare)
+ (NSDate*)laterDate:(NSDate*)date1
date:(NSDate*)date2 {
NSDate* laterDate ;
if (date1 != nil) {
if (date2 != nil) {
laterDate = [date1 laterDate:date2] ;
}
else {
laterDate = date1 ;
}
}
else {
laterDate = date2 ;
}
return laterDate ;
}
+ (BOOL)isEqualHandlesNilDate1:(NSDate*)date1
date2:(NSDate*)date2
tolerance:(NSTimeInterval)tolerance {
BOOL isEqual = NO ;
if (date1) {
if (!date2) {
// Documentation for -isEqual does not state if
// the argument can be nil, so for safety I handle that
// here, without invoking it.
// date2 is nil but object1 is not
// Leave isEqual as initialized, to NO.
}
else {
if (tolerance == 0.0) {
isEqual = [date1 isEqual:date2] ;
}
else {
NSTimeInterval t1 = [date1 timeIntervalSinceReferenceDate] ;
NSTimeInterval t2 = [date2 timeIntervalSinceReferenceDate] ;
NSTimeInterval diff = fabs(t2 - t1) ;
isEqual = diff <= tolerance ;
}
}
}
else if (date2) {
// object1 is nil but object2 is not
// Leave isEqual as initialized, to NO.
}
else {
isEqual = YES ;
}
return isEqual ;
}
@end