Search code examples
iosobjective-cdatetimensdatensdateformatter

Getting wrong time while converting from NSString to NSDate When Device Time format is 24hr


In Following Code I am trying to convert NSString to NSDate and once again converting to another Date format and sending it to server.

Following code worked perfectly fine when my Device Time Format is 12 hr. with dateformat to [dateFormatter setDateFormat:@"dd-MMM-yyyy hh:mm a"]; it gives me correct Date and Time.

But As soon as I changed device time Format to 24 hr. and change the datefomatter to [dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm a"]; it gives wrong Date and Time (Specifically time.) I had shown log values for code.

I had checked lot of stackoverflow questions regarding NSDateFormatter and Conversion of NSString to NSDate. But I am not able to find out where I'm making mistake and why it gives me wrong time when my Device time format is 24hr. Please help me to resolve this.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm a"];
NSString *fromTime = [NSString stringWithFormat:@"%@",@"04-Jul-2017 01:46 PM"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:fromTime];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSString *setdtFrom=[dateFormatter stringFromDate:dateFromString];
NSLog(@"From DateTime %@",setdtFrom);

Following log showing Date and Time When My Device Time format is 12hr. And it is Correct one.
From DateTime 2017-07-04T13:46:00

Time When My Device Time format is 24hr. And it is wrong (specifically time).
From DateTime 2017-07-04T12:46:00


Solution

  • Please try setting locale & timezone

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MMM-yyyy hh:mm a"];
        [dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier: @"en_US_POSIX"]];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *fromTime = [NSString stringWithFormat:@"%@",@"04-Jul-2017 01:46 PM"];
        NSDate *dateFromString = [dateFormatter dateFromString:fromTime];
        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
        NSString *setdtFrom=[dateFormatter stringFromDate:dateFromString];
        NSLog(@"From DateTime %@",setdtFrom);