objective-c - 将字符串转换为日期会损失一个小时

标签 objective-c timezone nsdate

我正在尝试将字符串格式的日期转换为 NSDate,但是结果似乎从传入的时间中扣除了一个小时。有什么想法吗?

-(NSDate *) convertStringToDate:(NSString *)theString {

    //init formatter
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 

    //setup the formatter
    [dateFormat setDateFormat:@"dd-MM-yyyy HH:mm"];
    [dateFormat setTimeZone:[NSTimeZone localTimeZone]];  

    //cast the date from the string
    NSDate *date = [dateFormat dateFromString:theString];


    [dateFormat release];

    return date;    
}

这是测试调用:

NSDate *testDate = [self convertStringToDate:@"28-03-2012 11:46"];    
NSLog(@"converted test date - %@", testDate);

我得到输出(这是我指定为参数的时间之前的一个小时):

converted test date - 2012-03-28 10:46:00 +0000

任何有关如何更改时区的帮助将不胜感激。

最佳答案

当您 NSLog 一个 NSDate 时,它不会显示在您的本地时区中。它以 GMT 显示。您本地的时区目前比 GMT 早 1 小时(可能是因为夏令时)。

要将日期转换为相对于您本地时区的字符串,您需要使用日期格式化程序(默认情况下,日期格式化程序的时区将设置为您本地时区):

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
NSLog(@"converted test date - %@", [dateFormatter stringFromDate:testDate]);

关于objective-c - 将字符串转换为日期会损失一个小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9906069/

相关文章:

iPhone:是否可以通过编程方式启用/禁用电话功能?

ruby-on-rails - Rails 时区事件记录

python - Django 时区字段不接受所有 pytz 时区

iphone NSDate 转换问题

objective-c - 错误 : expected expression on line using #defined constant

ios - 将 PFObject 分配给 UILabel - 将 PFUser 转换为 NSString 值?

objective-c - NSURLSession/NSURLConnection HTTP 加载失败 (kCFStreamErrorDomainSSL, -9802) https 连接错误

Javascript 使用 momentjs 在时区之间进行转换

ios - 在 NSDate 调用方法

iphone - [NSDate日期]是如何计算的?