oOOMIAO
2013-04-18 09:09
采纳率: 66%
浏览 2.1k
已采纳

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 2013-04-22 07: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)

    打赏 评论

相关推荐 更多相似问题