Skip to content

Instantly share code, notes, and snippets.

@rsaunders100
Created February 13, 2014 09:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsaunders100/8972207 to your computer and use it in GitHub Desktop.
Save rsaunders100/8972207 to your computer and use it in GitHub Desktop.
NSDateFormatter reuse
// 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;
}
@rsaunders100
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment