首页 文章

为什么我的时区没有保存到我的NSDate中?

提问于
浏览
15

我必须在objective-c中从NSString初始化一个NSDate对象 . 我是这样做的:

NSString *dateString = [[webSentence child:@"DateTime"].text stringByReplacingOccurrencesOfString:@"T" withString:@" "];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Budapest"]];

NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];

例如:当我尝试使用字符串值@“2011-01-02 17:49:54”时,我得到一张NSDate 2011-01-02 16:49:54 0000.正如你所看到的,它之间有一个小时的差异两个值 . NSDate有一个错误的值,它应该与我在dateFormatter中设置的时区中的字符串中定义的完全相同 . 它似乎使用我的日期将字符串定义为UTC,即使我将其时区设置为“Europe / Budapest” . 我该如何解决这个问题?

谢谢!

2 回答

  • 27

    两件事情:

    1)您的日期格式字符串中有错误 . 您应该使用 MM 作为月份,而不是 mm (小写mm表示分钟)

    2)创建NSDate对象后,您需要使用NSDateFormatter方法 stringFromDate: 生成本地化为特定时区的日期字符串 . 如果您只是在NSDate对象上执行直接NSLog(),它将默认显示为GMT(GMT比布达佩斯时间晚一个小时)

  • 14

    NSDate存储相对于标准参考日期的日期 . 来自 class 文档:

    “NSDate的唯一原始方法timeIntervalSinceReferenceDate为NSDate接口中的所有其他方法提供了基础 . 此方法返回相对于绝对参考日期的时间值 - 2001年1月1日的第一个时刻,GMT . ”

    NSDate本身没有任何时区概念 . 因此,NSDateFormatter做了正确的事情:它转换了一个日期,你告诉它有一个GMT偏移(通过指定一个时区),并为你提供了该日期的“标准化”NSDate .

    如果要查看欧洲/布达佩斯时区中表示的日期,请使用现有的日期格式化程序(-stringFromDate :)或相应的NSDate描述方法(例如-descriptionWithCalendarFormat:timeZone:locale :) .

    P.S.-您的代码中根本不需要alloc / init . 在非ARC中,这将是一个泄漏 .

    P.P.S.-您的日期格式不正确,并给出了荒谬的结果 . 我已按照以下方式清理您的代码(在ARC下测试):

    NSString *dateString = @"2011-09-02 17:49:54";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"Europe/Budapest"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [dateFormatter setTimeZone:tz];
    
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSLog(@"%@", [dateFormatter stringFromDate:date]);
    NSLog(@"%@", [date descriptionWithCalendarFormat:nil timeZone:tz locale:nil]);
    

相关问题