From 4b2dc21ef88963a37964e5d6c9e0dc301bb63da0 Mon Sep 17 00:00:00 2001 From: Romain Champourlier Date: Thu, 18 Apr 2013 12:12:05 +0200 Subject: [PATCH] Reviewed DateFormatter used for date conversion Reviewed how the DateFormatter is created to follow Apple's guidelines and demo implementation provided in this documentation: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html IMO, it makes more sense not to consider user locale since we generally are parsing dates from a backend API, not user entered data. If we don't do it this way, it seems the dates will be converted using local settings, such as non-Gregorian calendar, AM/PM preferences, etc. --- KeyValueObjectMapping/DCNSDateConverter.m | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/KeyValueObjectMapping/DCNSDateConverter.m b/KeyValueObjectMapping/DCNSDateConverter.m index 889dfcc..8d17b34 100644 --- a/KeyValueObjectMapping/DCNSDateConverter.m +++ b/KeyValueObjectMapping/DCNSDateConverter.m @@ -10,6 +10,7 @@ @interface DCNSDateConverter() @property(nonatomic, strong) NSString *pattern; - (BOOL) validDouble: (NSString *) doubleValue; +- (NSDateFormatter *)dateFormatter; @end @implementation DCNSDateConverter @@ -32,8 +33,7 @@ - (id)transformValue:(id)value forDynamicAttribute:(DCDynamicAttribute *)attribu if(validDouble){ return [NSDate dateWithTimeIntervalSince1970:[value doubleValue]]; }else{ - NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; - formatter.dateFormat = self.pattern; + NSDateFormatter *formatter = [self dateFormatter]; return [formatter dateFromString:value]; } } @@ -48,4 +48,20 @@ - (BOOL) canTransformValueForClass: (Class) class { - (BOOL) validDouble: (NSString *) doubleValue { return [[[NSNumberFormatter alloc] init] numberFromString:doubleValue] != nil; } + + +#pragma mark - Private Methods + +- (NSDateFormatter *)dateFormatter { + + NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; + NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; + + [dateFormatter setLocale:enUSPOSIXLocale]; + [dateFormatter setDateFormat:self.pattern]; + [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; + + return dateFormatter; +} + @end