-
Notifications
You must be signed in to change notification settings - Fork 3
/
NSDate+Helper.m
executable file
·797 lines (630 loc) · 27.2 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//
// NSDate+Helper.m
// Codebook
//
// Created by Billy Gray on 2/26/09.
// Copyright 2009 Zetetic LLC. All rights reserved.
//
#import "NSDate+Helper.h"
#import "NSString+extensions.h"
NSString * PrettyDateFromInterval( NSInteger epoch ) {
// kindly adapted from Craig Francis at http://www.php.net/manual/en/function.time.php#74652
//--------------------------------------------------
// Maths
int sec = epoch % 60;
epoch -= sec;
int minSeconds = epoch % 3600;
epoch -= minSeconds;
int min = (minSeconds / 60);
int hourSeconds = epoch % 86400;
epoch -= hourSeconds;
int hour = (hourSeconds / 3600);
int daySeconds = epoch % 604800;
epoch -= daySeconds;
int day = (daySeconds / 86400);
// int week = (epoch / 604800);
int weekSeconds = epoch % 2419200;
epoch -= weekSeconds;
int week = (weekSeconds / 604800);
// int month = (epoch / 2419200);
int monthSeconds = epoch % 29030400;
epoch -= monthSeconds;
int month = (monthSeconds / 2419200);
int year = (epoch / 29030400);
//--------------------------------------------------
// Text
NSString * singleOutput;
if (year > 0) {
singleOutput = [NSString stringWithFormat:@"%d year%@" , year , (
year != 1 ? @"s" : @"")];
}
else if (month > 0) {
singleOutput = [NSString stringWithFormat:@"%d month%@" , month , (
month != 1 ? @"s" : @"")];
}
else if (week > 0) {
singleOutput = [NSString stringWithFormat:@"%d week%@" , week , (
week != 1 ? @"s" : @"")];
}
else if (day > 0) {
//output[] = day . ' day' . (day != 1 ? 's' : '');
singleOutput = [NSString stringWithFormat:@"%d day%@" , day , ( day
!= 1 ? @"s" : @"")];
}
else if (hour > 0) {
//output[] = hour . ' hour' . (hour != 1 ? 's' : '');
singleOutput = [NSString stringWithFormat:@"%d hour%@" , hour , (
hour != 1 ? @"s" : @"")];
}
else if (min > 0) {
//output[] = min . ' minute' . (min != 1 ? 's' : '');
singleOutput = [NSString stringWithFormat:@"%d min%@" , min , ( min
!= 1 ? @"s" : @"")];
}
else {
//output[] = sec . ' second' . (sec != 1 ? 's' : '');
singleOutput = [NSString stringWithFormat:@"%d sec%@" , sec , ( sec
!= 1 ? @"s" : @"")];
}
// [singleOutput retain];
//--------------------------------------------------
// Grammar
/*
if( isset(max_phrases) )
output = array_slice(output, 0, max_phrases);
return = join( ', ', output);
return = preg_replace('/, ([^,]+)/', ' and 1', return);
//--------------------------------------------------
// Return the output
return return;
*/
return singleOutput;
}
NSString* prettyHoursFromInterval(NSTimeInterval seconds){
float hours = ((float)seconds/(60.0*60.0));
float halfHours = roundf(hours/.5)*.5;
return [NSString stringWithFormat:@"%.1f hours", halfHours];
}
NSString* prettyHoursFromIntervalNumberOnly(NSTimeInterval seconds){
float hours = ((float)seconds/(60.0*60.0));
float halfHours = roundf(hours/.5)*.5;
return [NSString stringWithFormat:@"%.1f", halfHours];
}
NSString* prettyMinutesAndSecondsFromInterval(NSTimeInterval seconds){
float minutes = floorf(((float)seconds)/60);
float leftoverSeconds = roundf(((float)seconds) - minutes * 60);
NSString* secString = nil;
if(leftoverSeconds < 10){
secString = [NSString stringWithFormat:@"0%.0f", leftoverSeconds];
}else{
secString = [NSString stringWithFormat:@"%.0f", leftoverSeconds];
}
return [NSString stringWithFormat:@"%.0f:%@", minutes, secString];
}
@implementation NSDate (Helper)
/*
* This guy can be a little unreliable and produce unexpected results,
* you're better off using daysAgoAgainstMidnight
*/
- (NSUInteger)daysAgo {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit)
fromDate:self
toDate:[NSDate date]
options:0];
return [components day];
}
- (NSUInteger)daysAgoAgainstMidnight {
// get a midnight version of ourself:
NSDateFormatter *mdf = [[NSDateFormatter alloc] init];
[mdf setDateFormat:@"yyyy-MM-dd"];
NSDate *midnight = [mdf dateFromString:[mdf stringFromDate:self]];
[mdf release];
return (int)[midnight timeIntervalSinceNow] / (60*60*24) *-1;
}
- (NSString *)stringDaysAgo {
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", daysAgo];
}
return text;
}
- (NSUInteger)weekday {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:(NSWeekdayCalendarUnit) fromDate:self];
return [weekdayComponents weekday];
}
+ (NSDate *)dateFromString:(NSString *)string {
return [NSDate dateFromString:string withFormat:[NSDate dbFormatString]];
}
+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format {
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:format];
NSDate *date = [inputFormatter dateFromString:string];
[inputFormatter release];
return date;
}
+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format {
return [date stringWithFormat:format];
}
+ (NSString *)stringFromDate:(NSDate *)date {
return [date string];
}
+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed {
/*
* 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];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *offsetComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:today];
NSDate *midnight = [calendar dateFromComponents:offsetComponents];
NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
NSString *displayString = nil;
// comparing against midnight
if ([date compare:midnight] == NSOrderedDescending) {
if (prefixed) {
[displayFormatter setDateFormat:@"'at' h:mm a"]; // at 11:30 am
} else {
[displayFormatter setDateFormat:@"h:mm a"]; // 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];
if ([date compare:lastweek] == NSOrderedDescending) {
[displayFormatter setDateFormat:@"EEEE"]; // 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) {
[displayFormatter setDateFormat:@"MMM d"];
} else {
[displayFormatter setDateFormat:@"MMM d, yyyy"];
}
}
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];
[displayFormatter release];
return displayString;
}
+ (NSString *)stringForDisplayFromDate:(NSDate *)date {
return [self stringForDisplayFromDate:date prefixed:NO];
}
- (NSString *)stringWithFormat:(NSString *)format {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:format];
NSString *timestamp_str = [outputFormatter stringFromDate:self];
[outputFormatter release];
return timestamp_str;
}
- (NSString *)string {
return [self stringWithFormat:[NSDate dbFormatString]];
}
- (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateStyle:dateStyle];
[outputFormatter setTimeStyle:timeStyle];
NSString *outputString = [outputFormatter stringFromDate:self];
[outputFormatter release];
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 @"yyyy-MM-dd";
}
+ (NSString *)timeFormatString {
return @"HH:mm:ss";
}
+ (NSString *)timestampFormatString {
return @"yyyy-MM-dd HH:mm:ss";
}
// preserving for compatibility
+ (NSString *)dbFormatString {
return [NSDate timestampFormatString];
}
@end
@implementation NSDate (Misc)
+ (NSDate *)dateWithoutTime
{
return [[NSDate date] dateAsDateWithoutTime];
}
-(NSDate *)dateByAddingDays:(NSInteger)numDays
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:numDays];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:self options:0];
[comps release];
[gregorian release];
return date;
}
-(NSDate *)dateByAddingDays:(NSInteger)numDays hours:(NSInteger)numHours minutes:(NSInteger)numMinutes
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:numDays];
[comps setHour:numHours];
[comps setMinute:numMinutes];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:self options:0];
[comps release];
[gregorian release];
return date;
}
- (NSDate *)dateAsDateWithoutTime
{
NSString *formattedString = [self formattedDateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd, yyyy"];
NSDate *ret = [formatter dateFromString:formattedString];
[formatter release];
return ret;
}
- (int)differenceInDaysTo:(NSDate *)toDate
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSDayCalendarUnit
fromDate:self
toDate:toDate
options:0];
NSInteger days = [components day];
[gregorian release];
return days;
}
- (NSString *)formattedDateString
{
return [self formattedStringUsingFormat:@"MMM dd, yyyy"];
}
- (NSString *)formattedStringUsingFormat:(NSString *)dateFormat
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:dateFormat];
NSString *ret = [formatter stringFromDate:self];
[formatter release];
return ret;
}
- (NSString*)prettyAge{
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSMonthCalendarUnit | NSYearCalendarUnit;
NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:self toDate:[NSDate date] options:0];
return [NSString stringWithFormat:@"%d years %d months", [breakdownInfo year], [breakdownInfo month]];
}
- (NSString*)durationInHoursAndMinutesSinceDate:(NSDate*)startDate{
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:startDate toDate:self options:0];
NSString* minutes = nil;
if([breakdownInfo minute] < 10){
minutes = [NSString stringWithFormat:@"0%d", [breakdownInfo minute]];
}else{
minutes = [NSString stringWithFormat:@"%d", [breakdownInfo minute]];
}
return [NSString stringWithFormat:@"%d:%@", [breakdownInfo hour], minutes];
}
@end
@implementation NSDate (MoreHelp)
+ (NSDate*)dateWithString:(NSString*)dateString formatString:(NSString*)dateFormatterString {
if(!dateString) return nil;
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:dateFormatterString];
return [formatter dateFromString:dateString];
}
+ (NSDate*)dateWithISO8601String:(NSString*)dateString {
if(!dateString) return nil;
if([dateString hasSuffix:@" 00:00"]) {
dateString = [[dateString substringToIndex:(dateString.length-6)] stringByAppendingString:@"GMT"];
} else if ([dateString hasSuffix:@"Z"]) {
dateString = [[dateString substringToIndex:(dateString.length-1)] stringByAppendingString:@"GMT"];
}
return [[self class] dateWithString:dateString formatString:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
}
+ (NSDate*)dateWithDateString:(NSString*)dateString {
return [[self class] dateWithString:dateString formatString:@"yyyy-MM-dd"];
}
+ (NSDate*)dateWithDateTimeString:(NSString*)dateString {
return [[self class] dateWithString:dateString formatString:@"yyyy-MM-dd HH:mm:ss"];
}
+ (NSDate*)dateWithLongDateTimeString:(NSString*)dateString {
return [[self class] dateWithString:dateString formatString:@"dd MMM yyyy HH:mm:ss"];
}
+ (NSDate*)dateWithRSSDateString:(NSString*)dateString {
if ([dateString hasSuffix:@"Z"]) {
dateString = [[dateString substringToIndex:(dateString.length-1)] stringByAppendingString:@"GMT"];
}
return [[self class] dateWithString:dateString formatString:@"EEE, d MMM yyyy HH:mm:ss ZZZ"];
}
+ (NSDate*)dateWithAltRSSDateString:(NSString*)dateString {
if ([dateString hasSuffix:@"Z"]) {
dateString = [[dateString substringToIndex:(dateString.length-1)] stringByAppendingString:@"GMT"];
}
return [[self class] dateWithString:dateString formatString:@"d MMM yyyy HH:mm:ss ZZZ"];
}
- (NSString*)formattedDateWithFormatString:(NSString*)dateFormatterString {
if(!dateFormatterString) return nil;
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:dateFormatterString];
[formatter setAMSymbol:@"am"];
[formatter setPMSymbol:@"pm"];
return [formatter stringFromDate:self];
}
- (NSString*)formattedDate {
return [self formattedDateWithFormatString:@"EEE, d MMM 'at' h:mma"];
}
- (NSString*)relativeFormattedDate {
// Initialize the formatter.
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
// Initialize the calendar and flags.
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
// Create reference date for supplied date.
NSDateComponents *comps = [calendar components:unitFlags fromDate:self];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate* suppliedDate = [calendar dateFromComponents:comps];
// Iterate through the eight days (tomorrow, today, and the last six).
int i;
for (i = -1; i < 7; i++) {
// Initialize reference date.
comps = [calendar components:unitFlags fromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
[comps setDay:[comps day] - i];
NSDate* referenceDate = [calendar dateFromComponents:comps];
// Get week day (starts at 1).
int weekday = [[calendar components:unitFlags fromDate:referenceDate] weekday] - 1;
if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == 0) {
// Today
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
break;
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == 1) {
// Yesterday
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithString:LocalizedString(@"Yesterday")];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame) {
// Day of the week
return [[formatter weekdaySymbols] objectAtIndex:weekday];
}
}
// It's not in those eight days.
return [formatter stringFromDate:self];
}
- (NSString*)relativeFormattedDateOnly {
// Initialize the formatter.
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
// Initialize the calendar and flags.
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
// Create reference date for supplied date.
NSDateComponents *comps = [calendar components:unitFlags fromDate:self];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate* suppliedDate = [calendar dateFromComponents:comps];
// Iterate through the eight days (tomorrow, today, and the last six).
int i;
for (i = -1; i < 7; i++) {
// Initialize reference date.
comps = [calendar components:unitFlags fromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
[comps setDay:[comps day] - i];
NSDate* referenceDate = [calendar dateFromComponents:comps];
// Get week day (starts at 1).
int weekday = [[calendar components:unitFlags fromDate:referenceDate] weekday] - 1;
if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == 0) {
// Today
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithString:LocalizedString(@"Today")];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == 1) {
// Yesterday
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithString:LocalizedString(@"Yesterday")];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == -1) {
// Yesterday
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithString:LocalizedString(@"Tomorrow")];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame) {
// Day of the week
return [[formatter weekdaySymbols] objectAtIndex:weekday];
}
}
// It's not in those eight days.
return [formatter stringFromDate:self];
}
- (NSString*)relativeFormattedDateTime {
// Initialize the formatter.
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setAMSymbol:@"am"];
[formatter setPMSymbol:@"pm"];
// Initialize the calendar and flags.
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
// Create reference date for supplied date.
NSDateComponents *comps = [calendar components:unitFlags fromDate:self];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate* suppliedDate = [calendar dateFromComponents:comps];
// Iterate through the eight days (tomorrow, today, and the last six).
int i;
for (i = -1; i < 7; i++) {
// Initialize reference date.
comps = [calendar components:unitFlags fromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
[comps setDay:[comps day] - i];
NSDate* referenceDate = [calendar dateFromComponents:comps];
// Get week day (starts at 1).
int weekday = [[calendar components:unitFlags fromDate:referenceDate] weekday] - 1;
if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == 0) {
// Today
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithFormat:@"Today, %@", [formatter stringFromDate:self]];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == 1) {
// Yesterday
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithFormat:@"Yesterday, %@", [formatter stringFromDate:self]];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame) {
// Day of the week
NSString* day = [[formatter weekdaySymbols] objectAtIndex:weekday];
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithFormat:@"%@, %@", day, [formatter stringFromDate:self]];
}
}
// It's not in those eight days.
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
NSString* date = [formatter stringFromDate:self];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString* time = [formatter stringFromDate:self];
return [NSString stringWithFormat:@"%@, %@", date, time];
}
- (NSString*)relativeLongFormattedDate {
// Initialize the formatter.
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
// Initialize the calendar and flags.
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
// Create reference date for supplied date.
NSDateComponents *comps = [calendar components:unitFlags fromDate:self];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate* suppliedDate = [calendar dateFromComponents:comps];
// Iterate through the eight days (tomorrow, today, and the last six).
int i;
for (i = -1; i < 7; i++) {
// Initialize reference date.
comps = [calendar components:unitFlags fromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
[comps setDay:[comps day] - i];
NSDate* referenceDate = [calendar dateFromComponents:comps];
// Get week day (starts at 1).
int weekday = [[calendar components:unitFlags fromDate:referenceDate] weekday] - 1;
if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == 0) {
// Today
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithString:LocalizedString(@"Today")];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == 1) {
// Yesterday
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithString:LocalizedString(@"Yesterday")];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame && i == -1) {
// Tomorrow
[formatter setDateStyle:NSDateFormatterNoStyle];
return [NSString stringWithString:LocalizedString(@"Tomorrow")];
} else if ([suppliedDate compare:referenceDate] == NSOrderedSame) {
// Day of the week
return [[formatter weekdaySymbols] objectAtIndex:weekday];
}
}
// It's not in those eight days.
return [formatter stringFromDate:self];
}
- (NSString*)formattedTime {
// Initialize the formatter.
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
return [formatter stringFromDate:self];
}
- (NSString*)iso8601Formatted {
return [self formattedDateWithFormatString:@"yyyy-MM-dd'T'HH:mm:ssZ"];
}
- (BOOL)isPastDate {
NSDate* now = [NSDate date];
if([[now earlierDate:self] isEqualToDate:self]) {
return YES;
} else {
return NO;
}
}
- (NSDate*)midnightDate {
return [[NSCalendar currentCalendar] dateFromComponents:[[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self]];
}
@end