for_2012
for_2012
2013-07-10 06:37
采纳率: 70.7%
浏览 2.8k
已采纳

NSString转换到NSDate时日期不对

代码:

NSString * dateStr = @"7/25/2013 12:00:00 AM";    
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *date = [dateFormat dateFromString:dateStr];  
NSLog(@"dateStr : %@ , date : %@",dateStr,date);

但是转换的日期会比实际日期差一天:

dateStr : 7/25/2013 12:00:00 AM , date : 2013-07-24 18:30:00 +0000
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • xinyoulingxi1_tong
    xinyoulingxi1_tong 2013-07-10 07:11
    已采纳
    NSString * dateStr = @"7/25/2013 12:00:00 AM";
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
     [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDate *date = [dateFormat dateFromString:dateStr];
    
    NSLog(@"dateStr : %@ , date : %@",dateStr,date);
    

    试试看

    点赞 评论
  • Chengzi_963
    Chengzi_963 2013-07-10 07:42
     NSString * dateStr = @"7/25/2013 12:00:00 AM";
    
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
     [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
        [dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
        NSDate *date = [dateFormat dateFromString:dateStr];
    
    点赞 评论

相关推荐