summaryrefslogtreecommitdiffstats
path: root/Plugins/BuiltInFunctions/NaturalDateFormatter.m
blob: da83ee69ef980b337075854dcc29b90ee07768d4 (plain)
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
//
//  NaturalDateFormatter.m
//  BuiltInFunctions
//
//  Created by Brian Cully on Sun Aug 31 2003.
//  Copyright (c) 2003 Brian Cully. All rights reserved.
//

#import "NaturalDateFormatter.h"

#import "LiBuiltInFunctions.h"

static NSString *
myLocalizedString(NSString *aString)
{
    return NSLocalizedStringFromTableInBundle(aString, @"BuiltInFunctions",
                                              [LiBuiltInFunctions bundle], @"");
}

@implementation NaturalDateFormatter
- (id)initWithNaturalLanguage: (BOOL)flag
{
    NSString *format;

    format = [[NSUserDefaults standardUserDefaults] objectForKey: NSShortDateFormatString];

    self = [super initWithDateFormat: format allowNaturalLanguage: flag];
    return self;
}

- (NSString *)stringForObjectValue: (id)anObject
{
    NSString *stringValue;

    if ([anObject isKindOfClass: [NSDate class]]) {
        NSCalendarDate *testDate;
        int todayNum, myNum;

        testDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
            [(NSDate *)anObject timeIntervalSinceReferenceDate]];
        myNum = [[NSCalendarDate calendarDate] dayOfCommonEra];
        todayNum = [testDate dayOfCommonEra];
        if (myNum == todayNum)
            stringValue = myLocalizedString(@"Today");
        else if (todayNum == (myNum - 1))
            stringValue = myLocalizedString(@"Yesterday");
        else if (todayNum == (myNum + 1))
            stringValue = myLocalizedString(@"Tomorrow");
        else {
            stringValue = [testDate descriptionWithCalendarFormat:
                [self dateFormat]];
        }
    } else
        stringValue = [super stringForObjectValue: anObject];

    return stringValue;
}
@end