2 ooomiao oOOMIAO 于 2013.04.18 17:09 提问

NSDate转换结果失误

将下面的日期字符串转换成其他格式。操作如下:

NSLog(@"datestring is NOW %@",_dayObject.p_date);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-DD"];
NSDate *date = [dateFormat dateFromString:_dayObject.p_date];
NSLog(@"date transformed %@",date);
[dateFormat setDateFormat:@"EEEE, dd/MM/YYYY"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSString *dateStr = [dateFormat stringFromDate:date];
NSLog(@"datestring is AFTER %@",dateStr);

但是在NSLog中得到:

2013-04-18 08:43:36.181 mosaqua2[9629:907] datestring is NOW 2013-05-04
2013-04-18 08:43:36.184 mosaqua2[9629:907] date transformed 2013-01-03 23:00:00 +0000
2013-04-18 08:43:36.184 mosaqua2[9629:907] datestring is AFTER donderdag, 03/01/2013

正确的格式是: Saterday, 04/05/2013

谢谢您的解答。

1个回答

xiaoyaokk
xiaoyaokk   2013.04.22 15:37
已采纳
    NSLog(@"datestring is NOW %@",_dayObject.p_date);
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    NSTimeZone *GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    [dateFormat setDateFormat:@"YYYY-MM-dd"];
    [dateFormat setTimeZone:GTMzone];
    NSDate  *date = [dateFormat dateFromString:_dayObject.p_date];
    NSLog(@"date transformed %@",date);
    [dateFormat setDateFormat:@"EEEE, dd/MM/YYYY"];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    NSString *dateStr = [dateFormat stringFromDate:date];
    NSLog(@"datestring is AFTER %@",dateStr);

使用NSDateFormatter转换时间字符串时,默认的时区是系统时区,我们使用的一般都是北京时间(+8)

Csdn user default icon
上传中...
上传图片
插入图片