NSDateFormatter奇怪的行为

时间:2012-03-02 09:21:34

标签: ios json nsdateformatter

我正在开发一个带有最新SDK和XCode 4.2的iOs 4应用程序。

我正在使用JSON Web服务来获取一些数据。其中一个数据是日期。

要转换由SBJson解析的日期,我使用以下格式化程序:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];

我正在使用异步连接,当它从Web服务获取所有数据时,我使用此代码创建自己的对象:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    NSString *json_string = [[NSString alloc] initWithData:receivedData
                                                  encoding:NSUTF8StringEncoding];
    NSDictionary* datos = [parser objectWithString:json_string error:nil]; 

    [connection release];
    [receivedData release];
    [parser release];
    [json_string release];

    NSArray* data = [datos objectForKey:kRootKey];

    cierres = [[NSMutableArray alloc] initWithCapacity:data.count];

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];

    for (int i = 0; i < data.count; i++)
    {
        NSDictionary* object = [data objectAtIndex:i];

        NSLog(@"Parser: %@, Aper: %@, Cierre: %@", [object objectForKey:kFederacionKey], [object objectForKey:kAperturaKey], [object objectForKey:kCierreKey]);
        NSString* fedName = [object objectForKey:kFederacionKey];
        NSDate* aperDate = [df dateFromString: [object objectForKey:kAperturaKey]];
        NSDate* cierreDate = [df dateFromString: [object objectForKey:kCierreKey]];

        CierreData* cierreData =
            [[CierreData alloc] initWithFederationName:fedName
                                              openDate:aperDate
                                          andCloseDate:cierreDate];
        [cierres addObject:cierreData];

        [cierreData release];
    }

    [delegate dataReceived];
}

这句话NSLog(@"Parser: %@, Aper: %@, Cierre: %@", [object objectForKey:kFederacionKey], [object objectForKey:kAperturaKey], [object objectForKey:kCierreKey]);在控制台上显示以下输出:

Parser:Dinamarca,Aper:2012-01-05,Cierre:2012-01-31

但是,aperDate变量 2012-01-04 23:00:00 +0000

为什么我必须在2012-01-05获得2012-01-04?我还在我的网络浏览器上检查了JSON数据,并且是2012-01-05。

2 个答案:

答案 0 :(得分:2)

创建NSDate时,自动将时区设置为GMT0,因此您应将时区设置为NSDate,例如:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timezone = [NSTimeZone timeZoneWithName:@"Europe/Madrid"];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
[dateFormatter setTimeZone:timezone];

答案 1 :(得分:2)

您好,这段代码可以帮到您。试试这样。

 NSDateFormatter *formater=[[NSDateFormatter alloc]init];
        [formater setDateFormat:@"yyyy-MM-dd h:mm:ss a"];
        [formater setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

        NSDate *now1 = [formater dateFromString:[NSString stringWithFormat:@"%@ 11:07:00 PM",[[arrdate objectAtIndex:i]valueForKey:@"date"]]];

        NSLog(@"%@",now1);
相关问题