2013-08-21 119 views
-2

我以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和当地日期之间的时差。

它们的值,年,月,日,小时和分钟都被服务器正确设置和接收。我知道这是因为一些其他值正确显示。

但是这种日期 - 时间转换过程在少数情况下出错。

为什么发生?

由于它从来没有发生过我的设备,但发生在其他国家的用户,我不知道如何重现它。他们试图重新启动它,但他们仍然得到错误的日期。 谢谢。

+0

没有看到您的输入和输出,不可能找到您可能已经搞砸的所有地方。 (顺便说一句,-1表示当发生“iOS错误”的几率极小时)。 –

+0

您的代码绝对没有意义 - 您将字符串转换为NSDate,将其转换为字符串,然后再转换为NSDate,全部使用相同的日期格式化程序,并且不更改日期格式化程序设置。你期望改变什么? –

+0

(你怎么期望上面的格林威治标准时间转换为当地时间?) –

回答

1

您使用NSDateFormatter阅读或发出需要在某些特定格式的日期的任何时候,你会想要做这样的事情:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; 

这将避免显示的问题例如here

+0

那么,它会在任何地方工作吗?我的应用程序不仅以美国为中心,所以这样他们都可以使用它吗?谢谢。 –

+0

是的,这可以在任何地方工作,手动设置区域设置不会干扰您的应用程序的本地化。与时区不同;手动设置它是为了确保用户的设备按照您的预期行事,无论其语言或区域设置如何。 – bdesham

1

您无法按照QA1480的要求设置区域设置。因此,您设置的日期格式可能会根据用户的设置进行修改。

明确设置区域设置来解决问题。

相关问题