1//
2//  NSDate+TimeIntervalDescription.m
3//  Security
4//
5//  Created by J Osborne on 7/17/13.
6//
7//
8
9#import "NSDate+TimeIntervalDescription.h"
10#include <math.h>
11#import <Security/SecFrameworkStrings.h>
12#import <Foundation/NSObjCRuntime.h>
13
14@implementation NSDate (TimeIntervalDescription)
15
16-(NSString*)copyDescriptionOfIntervalSince:(NSDate *)originalDate
17{
18	// This is really expected to be "1 day", "N days" in production, but for testing we
19	// use very small intervals, and we may as well have that work out.
20	
21	NSTimeInterval seconds = [self timeIntervalSinceDate:originalDate];
22	if (seconds <= 0) {
23		return (__bridge_transfer NSString*)SecCopyCKString(SEC_CK_TID_FUTURE);
24	}
25	if (seconds == 0) {
26		return (__bridge_transfer NSString*)SecCopyCKString(SEC_CK_TID_NOW);
27	}
28	if (seconds < 1) {
29		return (__bridge_transfer NSString*)SecCopyCKString(SEC_CK_TID_SUBSECOND);
30	}
31	if (seconds < 120) {
32		return [NSString stringWithFormat:@"%d %@", (int)seconds, (__bridge_transfer NSString*)SecCopyCKString(SEC_CK_TID_SECONDS)];
33	}
34	if (seconds < 2*60*60) {
35		return [NSString stringWithFormat:@"%d %@", (int)seconds/60, (__bridge_transfer NSString*)SecCopyCKString(SEC_CK_TID_MINUTES)];
36	}
37	if (seconds < 60*60*24) {
38		return [NSString stringWithFormat:@"%d %@", (int)seconds/(60*60), (__bridge_transfer NSString*)SecCopyCKString(SEC_CK_TID_HOURS)];
39	}
40    
41    double days = nearbyint(seconds/(60*60*24));
42    // XXX "day" vs. "days"
43	return [NSString stringWithFormat:@"%.0f %@", days, (days == 1) ? (__bridge_transfer NSString*)SecCopyCKString(SEC_CK_TID_DAY) : (__bridge_transfer NSString*)SecCopyCKString(SEC_CK_TID_DAYS)];
44}
45
46@end
47