1

I'm converting 12 hour date to 24 here, but it failed to get perfect time. Here is code :

  NSString *dateStr = @"2016-08-12T04:10:14.915Z";
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"];
    [dateFormat setTimeZone:[NSTimeZone localTimeZone]];
    NSDate *date = [dateFormat dateFromString:dateStr];

and my final date is

2016-08-11 22:40:14 +0000

How ?

kb920
  • 3,039
  • 2
  • 33
  • 44
Kabali
  • 129
  • 1
  • 13

1 Answers1

0

The NSDate object that you are getting is GMT. In France GMT -2, if I run your code I have a time of 02:10.

Am I correct assuming your GMT offset is -5:30 ?

NSDate objects don't have time zones; they represent an absolute moment in time. However, when you ask one for its description (by printing it in an NSLog, e.g.), it has to pick a time zone. The most reasonable "default" choice is GMT. If you're not in GMT yourself, the date will seem to be incorrect, by the amount of your own offset.

You should always use an NSDateFormatter, setting its timezone to yours, before displaying a date.

Don't trust what NSLog or the debbuger are telling you about a NSDate. use

NSString dateAsString = [dateFormat stringFromDate:date];

to check your date :)

Florian Burel
  • 3,408
  • 1
  • 19
  • 20
  • if you use a NSDateFormatter set to [NSTimeZone localTimeZone]] to print the date later on, you'll have it correctly setup at 04:10 :) – Florian Burel Aug 12 '16 at 11:26
  • i already use localTimeZone in dateformate please see in question. – Kabali Aug 12 '16 at 11:28
  • and if i use [NSTimeZone timeZoneWithName:@"GMT"] than it not convert my 04(12Hr) to 24Hr. – Kabali Aug 12 '16 at 11:28
  • Yes, and there is no probleme with that. look at this thread for more answer : http://stackoverflow.com/questions/8466744/getting-date-from-nsdate-date-off-by-a-few-hours/38896078#38896078 – Florian Burel Aug 12 '16 at 11:31
  • i dont want to add GMT, i just want to conver 12 to 24 hr – Kabali Aug 12 '16 at 11:34
  • instead of looking at you final date object, print it in a NSString with [dateFormat stringFromDate:date]; and you will see, all is fine :) – Florian Burel Aug 12 '16 at 11:36