I'm storing values in GMT format on a server. I download them on the device and convert it to the users local time via the following function:
- (void)convertTimeZone
{
//Converts the match timing from GMT to the users local time
NSString *serverDateString = [NSString stringWithFormat:@"%@-%@-%@ %@:%@ GMT", year, month, day, hour, min];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm zzz";
NSDate *serverDate = [dateFormatter dateFromString:serverDateString];
NSString *localDateString = [dateFormatter stringFromDate:serverDate];
NSDate *localDate = [dateFormatter dateFromString:localDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit |NSMinuteCalendarUnit |NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:localDate];
min = [NSString stringWithFormat:@"%d",[components minute]];
hour = [NSString stringWithFormat:@"%d",[components hour]];
day = [NSString stringWithFormat:@"%d",[components day]];
month = [NSString stringWithFormat:@"%d",[components month]];
year = [NSString stringWithFormat:@"%d",[components year]];
}
Almost everybody gets the proper time after conversion. However few users have written in to say that the date they receive is 1st January 2001, which is the initialization date on iOS and OSX. And the date is the time difference between GMT and their local date.
They values year, month, day, hour and min are properly set and received by the server. I know that because some of the other values are displayed properly.
However this date-time conversion process goes wrong in few cases.
Why does it happen?
Since it has never happened on my device but has happened to users in other countries, I don't know how to reproduce it. They tried to restart it but they still get the wrong date. Thanks.