-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathNSDate+Helper.m
executable file
·298 lines (262 loc) · 11.4 KB
/
NSDate+Helper.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//
// NSDate+Helper.h
//
// Created by Billy Gray on 2/26/09.
// Copyright (c) 2009–2012, ZETETIC LLC
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the ZETETIC LLC nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#import "NSDate+Helper.h"
static NSString *kNSDateHelperFormatFullDateWithTime = @"MMM d, yyyy h:mm a";
static NSString *kNSDateHelperFormatFullDate = @"MMM d, yyyy";
static NSString *kNSDateHelperFormatShortDateWithTime = @"MMM d h:mm a";
static NSString *kNSDateHelperFormatShortDate = @"MMM d";
static NSString *kNSDateHelperFormatWeekday = @"EEEE";
static NSString *kNSDateHelperFormatWeekdayWithTime = @"EEEE h:mm a";
static NSString *kNSDateHelperFormatTime = @"h:mm a";
static NSString *kNSDateHelperFormatTimeWithPrefix = @"'at' h:mm a";
static NSString *kNSDateHelperFormatSQLDate = @"yyyy-MM-dd";
static NSString *kNSDateHelperFormatSQLTime = @"HH:mm:ss";
static NSString *kNSDateHelperFormatSQLDateWithTime = @"yyyy-MM-dd HH:mm:ss";
@implementation NSDate (Helper)
static NSCalendar *_calendar = nil;
static NSDateFormatter *_displayFormatter = nil;
+ (void)initializeStatics {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_calendar == nil) {
_calendar = [[NSCalendar currentCalendar] retain];
}
if (_displayFormatter == nil) {
_displayFormatter = [[NSDateFormatter alloc] init];
}
});
}
/*
* This guy can be a little unreliable and produce unexpected results,
* you're better off using daysAgoAgainstMidnight
*/
- (NSUInteger)daysAgo {
[[self class] initializeStatics];
NSDateComponents *components = [_calendar components:(NSDayCalendarUnit)
fromDate:self
toDate:[NSDate date]
options:0];
return [components day];
}
- (NSUInteger)daysAgoAgainstMidnight {
[[self class] initializeStatics];
// get a midnight version of ourself:
NSDateFormatter *mdf = _displayFormatter;
[mdf setDateFormat:@"yyyy-MM-dd"];
NSDate *midnight = [mdf dateFromString:[mdf stringFromDate:self]];
return (int)[midnight timeIntervalSinceNow] / (60*60*24) *-1;
}
- (NSString *)stringDaysAgo {
[[self class] initializeStatics];
return [self stringDaysAgoAgainstMidnight:YES];
}
- (NSString *)stringDaysAgoAgainstMidnight:(BOOL)flag {
NSUInteger daysAgo = (flag) ? [self daysAgoAgainstMidnight] : [self daysAgo];
NSString *text = nil;
switch (daysAgo) {
case 0:
text = @"Today";
break;
case 1:
text = @"Yesterday";
break;
default:
text = [NSString stringWithFormat:@"%d days ago", (int)daysAgo];
}
return text;
}
- (NSUInteger)weekday {
[[self class] initializeStatics];
NSDateComponents *weekdayComponents = [_calendar components:(NSWeekdayCalendarUnit) fromDate:self];
return [weekdayComponents weekday];
}
+ (NSDate *)dateFromString:(NSString *)string {
[self initializeStatics];
return [NSDate dateFromString:string withFormat:[NSDate dbFormatString]];
}
+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format {
[self initializeStatics];
[_displayFormatter setDateFormat:format];
NSDate *date = [_displayFormatter dateFromString:string];
return date;
}
+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format {
[self initializeStatics];
return [date stringWithFormat:format];
}
+ (NSString *)stringFromDate:(NSDate *)date {
[self initializeStatics];
return [date string];
}
+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed alwaysDisplayTime:(BOOL)displayTime {
[self initializeStatics];
/*
* if the date is in today, display 12-hour time with meridian,
* if it is within the last 7 days, display weekday name (Friday)
* if within the calendar year, display as Jan 23
* else display as Nov 11, 2008
*/
NSDate *today = [NSDate date];
NSDateComponents *offsetComponents = [_calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:today];
NSDate *midnight = [_calendar dateFromComponents:offsetComponents];
NSString *displayString = nil;
// comparing against midnight
NSComparisonResult midnight_result = [date compare:midnight];
if (midnight_result == NSOrderedDescending) {
if (prefixed) {
[_displayFormatter setDateFormat:kNSDateHelperFormatTimeWithPrefix]; // at 11:30 am
} else {
[_displayFormatter setDateFormat:kNSDateHelperFormatTime]; // 11:30 am
}
} else {
// check if date is within last 7 days
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay:-7];
NSDate *lastweek = [_calendar dateByAddingComponents:componentsToSubtract toDate:today options:0];
[componentsToSubtract release];
NSComparisonResult lastweek_result = [date compare:lastweek];
if (lastweek_result == NSOrderedDescending) {
if (displayTime) {
[_displayFormatter setDateFormat:kNSDateHelperFormatWeekdayWithTime];
} else {
[_displayFormatter setDateFormat:kNSDateHelperFormatWeekday]; // Tuesday
}
} else {
// check if same calendar year
NSInteger thisYear = [offsetComponents year];
NSDateComponents *dateComponents = [_calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:date];
NSInteger thatYear = [dateComponents year];
if (thatYear >= thisYear) {
if (displayTime) {
[_displayFormatter setDateFormat:kNSDateHelperFormatShortDateWithTime];
}
else {
[_displayFormatter setDateFormat:kNSDateHelperFormatShortDate];
}
} else {
if (displayTime) {
[_displayFormatter setDateFormat:kNSDateHelperFormatFullDateWithTime];
}
else {
[_displayFormatter setDateFormat:kNSDateHelperFormatFullDate];
}
}
}
if (prefixed) {
NSString *dateFormat = [_displayFormatter dateFormat];
NSString *prefix = @"'on' ";
[_displayFormatter setDateFormat:[prefix stringByAppendingString:dateFormat]];
}
}
// use display formatter to return formatted date string
displayString = [_displayFormatter stringFromDate:date];
return displayString;
}
+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed {
return [[self class] stringForDisplayFromDate:date prefixed:prefixed alwaysDisplayTime:NO];
}
+ (NSString *)stringForDisplayFromDate:(NSDate *)date {
return [self stringForDisplayFromDate:date prefixed:NO];
}
- (NSString *)stringWithFormat:(NSString *)format {
[_displayFormatter setDateFormat:format];
NSString *timestamp_str = [_displayFormatter stringFromDate:self];
return timestamp_str;
}
- (NSString *)string {
return [self stringWithFormat:[NSDate dbFormatString]];
}
- (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle {
[_displayFormatter setDateStyle:dateStyle];
[_displayFormatter setTimeStyle:timeStyle];
NSString *outputString = [_displayFormatter stringFromDate:self];
return outputString;
}
- (NSDate *)beginningOfWeek {
// largely borrowed from "Date and Time Programming Guide for Cocoa"
// we'll use the default calendar and hope for the best
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *beginningOfWeek = nil;
BOOL ok = [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek
interval:NULL forDate:self];
if (ok) {
return beginningOfWeek;
}
// couldn't calc via range, so try to grab Sunday, assuming gregorian style
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
/*
Create a date components to represent the number of days to subtract from the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today's Sunday, subtract 0 days.)
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];
beginningOfWeek = nil;
beginningOfWeek = [calendar dateByAddingComponents:componentsToSubtract toDate:self options:0];
[componentsToSubtract release];
//normalize to midnight, extract the year, month, and day components and create a new date from those components.
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:beginningOfWeek];
return [calendar dateFromComponents:components];
}
- (NSDate *)beginningOfDay {
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:self];
return [calendar dateFromComponents:components];
}
- (NSDate *)endOfWeek {
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
// to get the end of week for a particular date, add (7 - weekday) days
[componentsToAdd setDay:(7 - [weekdayComponents weekday])];
NSDate *endOfWeek = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
[componentsToAdd release];
return endOfWeek;
}
+ (NSString *)dateFormatString {
return kNSDateHelperFormatSQLDate;
}
+ (NSString *)timeFormatString {
return kNSDateHelperFormatSQLTime;
}
+ (NSString *)timestampFormatString {
return kNSDateHelperFormatSQLDateWithTime;
}
// preserving for compatibility
+ (NSString *)dbFormatString {
return [NSDate timestampFormatString];
}
@end