Created
July 30, 2013 06:22
-
-
Save ryandevore/6110715 to your computer and use it in GitHub Desktop.
Utility class for caching NSDateFormatters, as suggested by:
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
extern NSString * const kUURFC3339DateFormatter; | |
@interface UUDateFormatter : NSObject | |
+ (NSDate*) dateFromRfc3339String:(NSString*)string; | |
+ (NSDate*) dateFromString:(NSString*)string withFormat:(NSString*)format; | |
+ (NSString*) dateToRfc3339String:(NSDate*)date; | |
+ (NSString*) dateToString:(NSDate*)date withFormat:(NSString*)format; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "UUDateFormatter.h" | |
static NSMutableDictionary* theSharedDateFormatterCache = nil; | |
NSString * const kUURFC3339DateFormatter = @"yyyy-MM-dd'T'HH:mm:ssZZ"; | |
@implementation UUDateFormatter | |
+ (NSDate*) dateFromRfc3339String:(NSString*)string | |
{ | |
return [self dateFromString:string withFormat:kUURFC3339DateFormatter]; | |
} | |
+ (NSDate*) dateFromString:(NSString*)string withFormat:(NSString*)format | |
{ | |
NSDateFormatter* df = [self getDateFormatter:format]; | |
return [df dateFromString:string]; | |
} | |
+ (NSString*) dateToRfc3339String:(NSDate*)date | |
{ | |
return [self dateToString:date withFormat:kUURFC3339DateFormatter]; | |
} | |
+ (NSString*) dateToString:(NSDate*)date withFormat:(NSString*)format | |
{ | |
NSDateFormatter* df = [self getDateFormatter:format]; | |
return [df stringFromDate:date]; | |
} | |
+ (NSMutableDictionary*) sharedCache | |
{ | |
if (theSharedDateFormatterCache == nil) | |
{ | |
theSharedDateFormatterCache = [[NSMutableDictionary alloc] init]; | |
} | |
return theSharedDateFormatterCache; | |
} | |
+ (NSDateFormatter*) getDateFormatter:(NSString*)formatter | |
{ | |
NSMutableDictionary* cache = [self sharedCache]; | |
NSDateFormatter* df = [cache valueForKey:formatter]; | |
if (df == nil) | |
{ | |
df = [[NSDateFormatter alloc] init]; | |
[df setDateFormat:formatter]; | |
[cache setValue:df forKey:formatter]; | |
} | |
return df; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment