Ahmed Mli Ahmed Mli - 3 months ago 15
Objective-C Question

Objective C - Converting time from 12 to 24 format issue

I'm converting the time from 12 to 24 format using the below code and its working fine, but the result is less than the actual time by 3 hours!
i.e : if the time is "12:40 pm", I am getting "09:40" after converting to 24 format.

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:strDate4Convert];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];


Thanks in advance;

Answer

Try to set timeZone to UTC or your localTimeZone instead of systemTimeZone.

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//Or [df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:@"12/02/2016 12:40 pm"];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];
Comments