【问题标题】:NSDate returning GMT timeNSDate 返回格林威治标准时间
【发布时间】:2013-06-01 13:34:14
【问题描述】:

我住在印度,格林威治标准时间 +5.30 小时。当我打印系统时间时,它会显示当前时间。但是当我使用这段代码时,使用的是 GMT 时间!

代码示例:

NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTimeInterval:24 * 60 * 60];
NSDate *dayaftertomorrow = [now dateByAddingTimeInterval:48 * 60 * 60];

NSLog(@"Tomorrow, the date will be %@" , tomorrow);
NSLog(@"Day after tomorrow, the date will be %@" , dayaftertomorrow);

现在的系统时间是晚上 11:34。但控制台打印出来:

2013-06-05 23:35:02.577 prog1[1601:303] 明天,日期是 2013-06-06 18:05:02 +0000 2013-06-05 23:35:02.578 prog1[1601:303] 后天,日期为2013-06-07 18:05:02 +0000

【问题讨论】:

    标签: cocoa timezone nsdate


    【解决方案1】:

    创建 NSDate 对象后,您必须使用 NSDateFormatter 方法 stringFromDate: 来生成本地化到特定时区的日期字符串。如果您只是在 NSDate 对象上直接执行 NSLog() ,它将默认将日期显示为 GMT

    【讨论】:

    • 澄清一下:NSDate 对象单独代表线性时间中的一个时刻,独立于任何时区。当您打印它或以其他方式显示它时,它会打印出某个时区中的哪一天和什么时间代表那个时刻(例如,“在格林威治标准时间,那个时刻是 6 月 6 日的 18:05”)。如果您希望它在特定时区(包括用户的时区)打印或显示,请使用您设置为使用该时区的日期格式化程序。
    【解决方案2】:

    您可以使用NSDateFormatter

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    
    NSLog(@"Now: %@", [dateFormatter stringFromDate:[NSDate date]]);
    

    可以使用NSTimeZone 找到其他时区,如下所示:

    NSLog(@"Timezones: %@", [NSTimeZone knownTimeZoneNames]);
    

    希望有帮助!

    【讨论】:

    • 非常感谢!干杯! :)
    猜你喜欢
    • 2011-02-04
    • 2011-05-13
    • 2013-03-10
    • 1970-01-01
    • 2011-10-30
    • 2010-12-02
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多