-1

My code:

    NSString *dateStr = @"03-02-2017";//[responseObject objectForKey:@"event_date"];
    NSLog(@"'%@'", dateStr);
    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_HK"];
    [dateFormat setLocale:locale]; //To fix the format into something like: 10 Feb 2017, but not: 10 2月 2017
    [dateFormat setDateFormat:@"dd-MM-YYYY"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    NSLog(@"'%@'", date);
    // Convert date object to desired output format
    [dateFormat setDateFormat:@"dd MMM YYYY"];
    dateStr = [dateFormat stringFromDate:date];
    NSLog(@"'%@'", dateStr);

And in log it returns

'03-02-2017'

'2016-12-24 16:00:00 +0000'

'25 Dec 2016'

Anyone know why this happened? I searched in google that most cases are causing by timezone. However, I'm pretty sure it's not about timeZone because the difference of dates are too large, but I can't figure out the root of this problem.

Community
  • 1
  • 1
KTang
  • 340
  • 1
  • 17

2 Answers2

1

I think your dateformat is wrong.

It should be

dd-MM-yyyy
fengd
  • 7,551
  • 3
  • 41
  • 44
0

I found that my format is wrong from answer objective-c - NSDateFormatter returns wrong date

and reference by http://nsdateformatter.com . It should be "yyyy" instead of "YYYY"

Community
  • 1
  • 1
KTang
  • 340
  • 1
  • 17