从NSString转换为NSDate时,日期会有所不同

时间:2013-07-09 12:08:51

标签: iphone ios nsdateformatter

这是我的代码

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

我做错了什么?

3 个答案:

答案 0 :(得分:1)

试试这个。

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);

答案 1 :(得分:0)

尝试这样的事情。这会对你有所帮助

 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];

答案 2 :(得分:0)

 NSString * dateStr = @"7/25/2013 12:00:00 AM";
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    [dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
    NSDate *date = [dateFormat dateFromString:dateStr];

    NSLog(@"dateStr : %@ , date : %@",dateStr,date);

设置时区可解决此问题