我以GMT格式在服务器上存储值。 我下载他们的设备上,并通过以下功能转换到用户本地时间:NSDateFormatter返回2001年1月1日作为日期
- (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]];
}
几乎每个人都得到转换后的适当时间。然而,很少有用户写道,他们收到的日期是2001年1月1日,这是iOS和OSX上的初始化日期。 而日期是GMT和当地日期之间的时差。
它们的值,年,月,日,小时和分钟都被服务器正确设置和接收。我知道这是因为一些其他值正确显示。
但是这种日期 - 时间转换过程在少数情况下出错。
为什么发生?
由于它从来没有发生过我的设备,但发生在其他国家的用户,我不知道如何重现它。他们试图重新启动它,但他们仍然得到错误的日期。 谢谢。
没有看到您的输入和输出,不可能找到您可能已经搞砸的所有地方。 (顺便说一句,-1表示当发生“iOS错误”的几率极小时)。 –
您的代码绝对没有意义 - 您将字符串转换为NSDate,将其转换为字符串,然后再转换为NSDate,全部使用相同的日期格式化程序,并且不更改日期格式化程序设置。你期望改变什么? –
(你怎么期望上面的格林威治标准时间转换为当地时间?) –