2 for 2012 for_2012 于 2013.07.10 14:37 提问

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 15: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 15: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];
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!