NSDateFormatter问题

时间:2010-07-30 10:31:37

标签: iphone nsdate nsdateformatter

嘿,我的日期为“7/30/2010”。我如何打印它只作为月和日,即。 “7/30” 我尝试使用NSFormatter但它打印的是我当前的日期而不是我的数据库中的日期。

2 个答案:

答案 0 :(得分:0)

您可以为NSDate添加一些utility methods

以下是示例标题:

@interface NSDate (Utilities)

+ (NSDate *) customDateForString:(NSString *)dateString;
+ (NSDateFormatter *) customDateFormatter;

@end

实施:

@implementation NSDate (Utilities)

static NSDateFormatter *customDateFormatter = nil;

+ (NSDateFormatter *) customDateFormatter {
    // Example: 7/30
    if (!customDateFormatter) {
        customDateFormatter = [[NSDateFormatter alloc] init];
        [customDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
        [customDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];

        // cf. http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
        [customDateFormatter setDateFormat:@"M/d"];
    }  
    return customDateFormatter;
}

+ (NSDate *) customDateForString:(NSString *)dateString {
    return [[self customDateFormatter] dateFromString:dateString];
}

@end

每当你需要解析一个日期字符串时,你会这样称呼它:

NSLog(@"Parsed date: %@", [NSDate customDateForString:@"7/30/2010"]); // Parsed date: 7/30

答案 1 :(得分:0)

NSDate *date = dateFromYourDataBase;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"M/dd"];
NSLog(@"%@", [formatter stringFromDate:date]);
[formatter release];