0

Needs some help with the following code:

self.dateTimestamp = userInfo[@"timestamp"];<- Returns UTC Time April 09 2018 11:09
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd YYYY HH:mm"];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setCalendar:[NSCalendar currentCalendar]];
NSDate *dte = [dateFormat dateFromString:self.dateTimestamp];
NSLog(@"Date: %@", dte); <-Date: Sun Dec 24 11:09:00 2017

Why do I have a date disparity.

Duny
  • 215
  • 4
  • 11
  • Possible duplicate of [NSDateFormatter show wrong year](https://stackoverflow.com/questions/12423179/nsdateformatter-show-wrong-year) – vadian Apr 09 '18 at 11:25
  • Time Zone should be UTC, I also think you should set locale en_US_POSIX if you always get month in english. – Cy-4AH Apr 09 '18 at 11:47
  • I suggest you to use "yyyy" instead of "YYYY" to retrieve years. See the difference : https://stackoverflow.com/a/15133617/5154891 – Thomas Mary Apr 09 '18 at 12:15
  • @ThomasMary i will give that try, i did't think that would make a different, but this might be one of those moments. – Duny Apr 09 '18 at 13:01

1 Answers1

2

Just replace YYYY by yyyy:

NSString *dateTimestamp = @"April 09 2018 13:07";

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd yyyy HH:mm"];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setCalendar:[NSCalendar currentCalendar]];

NSDate *dte = [dateFormat dateFromString:dateTimestamp];

NSLog(@"Date: %@", dte);

Result : Mon Apr 9 13:07:00 2018

But When using

[dateFormat setDateFormat:@"MMMM dd YYYY HH:mm"];

It's logging : Sun Dec 24 13:07:00 2017

Sulthan
  • 128,090
  • 22
  • 218
  • 270
Thomas Mary
  • 1,535
  • 1
  • 13
  • 24