Skip to content

Commit f3df53d

Browse files
author
Lucas Vidal
committed
Fix: force date parser to use military hours
This fixes an issue that occurs when device is set to use am/pm hour format and trying to parse iso 8601 datetimes, on which cases it retrieves nil. Also dateFormatter is stored in static reference to avoid multiple allocations when parsing, improving performance.
1 parent 2cdc5e4 commit f3df53d

1 file changed

Lines changed: 15 additions & 8 deletions

File tree

JSONModel/JSONModelTransformations/JSONValueTransformer.m

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ extern BOOL isNull(id value)
2626
return NO;
2727
}
2828

29+
static NSDateFormatter *_dateFormatter;
30+
2931
@implementation JSONValueTransformer
3032

3133
-(id)init
@@ -205,21 +207,26 @@ -(NSString*)JSONObjectFromNSURL:(NSURL*)url
205207
}
206208

207209
#pragma mark - string <-> date
210+
- (void) initDateFormatter
211+
{
212+
_dateFormatter = [[NSDateFormatter alloc] init];
213+
[_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HHmmssZZZZ"];
214+
[_dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]]; //this will force to parse datetimes in military format
215+
}
216+
208217
-(NSDate*)__NSDateFromNSString:(NSString*)string
209218
{
210-
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
219+
//avoid multiple allocations when parsing dates by using a static reference
220+
if (!_dateFormatter) [self initDateFormatter];
211221
string = [string stringByReplacingOccurrencesOfString:@":" withString:@""]; // this is such an ugly code, is this the only way?
212-
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HHmmssZZZZ"];
213-
214-
return [dateFormatter dateFromString: string];
222+
return [_dateFormatter dateFromString: string];
215223
}
216224

217225
-(NSString*)__JSONObjectFromNSDate:(NSDate*)date
218226
{
219-
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
220-
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
221-
222-
return [dateFormatter stringFromDate:date];
227+
//avoid multiple allocations when parsing dates by using a static reference
228+
if (!_dateFormatter) [self initDateFormatter];
229+
return [_dateFormatter stringFromDate:date];
223230
}
224231

225232
#pragma mark - hidden transform for empty dictionaries

0 commit comments

Comments
 (0)