Created
February 13, 2014 09:24
-
-
Save rsaunders100/8972207 to your computer and use it in GitHub Desktop.
NSDateFormatter reuse
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
// For NSString to NSDate to parse server dates in the full ISO 8601 format | |
// E.g. 2014-02-11T10:22:46+00:00 | |
+ (NSDateFormatter *) iso8601FullDateFromatter | |
{ | |
static NSDateFormatter * dateFormatter; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
dateFormatter = [[NSDateFormatter alloc] init]; | |
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; | |
[dateFormatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]]; | |
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; | |
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; | |
}); | |
return dateFormatter; | |
} | |
// For NSDate to NSString to display to the user | |
// E.g. 'Nov 23, 1937' | |
+ (NSDateFormatter *) userOutputDateOnlyFormatter | |
{ | |
static NSDateFormatter * dateFormatter; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
dateFormatter = [[NSDateFormatter alloc] init]; | |
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; | |
[dateFormatter setTimeStyle:NSDateFormatterNoStyle]; | |
[dateFormatter setCalendar:[NSCalendar currentCalendar]]; | |
[dateFormatter setLocale:[NSLocale currentLocale]]; | |
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]]; | |
}); | |
return dateFormatter; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an example of how you should configure NSDateFormatter objects properties for two separate purposes. It also demonstrates a reuse pattern to avoid performance issues.
It is part of my blog post on NSDateFormatters
http://www.rsaunders.co.uk/2014/02/date-parsing.html