【问题标题】:Unexpected output from NSDateNSDate 的意外输出
【发布时间】:2012-05-06 17:15:34
【问题描述】:

当我尝试注销当前日期时,我得到的日期与实际日期不同:

NSLog(@"date %@",[NSDate date]);

输出 2012-04-25 23:59:28 +0000

我的机器时间 2012-04-26 2:02 AM

任何人都知道如何解决这个问题?谢谢

编辑

这是我在使用 nsdataformatter 时得到的结果

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
[formatter setTimeZone:[NSTimeZone defaultTimeZone]];
NSDate *date =[formatter dateFromString:[NSString stringWithString:@"2012-04-26 01:00:00"]];
 NSLog(@"date %@",date);

输出:2012-04-25 23:00:00 +0000 混乱!

【问题讨论】:

标签: objective-c ios xcode nsdate


【解决方案1】:

没有什么可以解决的。 NSLog 以 GMT/UTC 格式输出日期。如果您想在本地时区使用它,则需要使用 NSDateFormatter。

【讨论】:

  • @mbg1987 -- 告诉我们你在哪里尝试使用 NSDateFormatter 来格式化日期。
【解决方案2】:

这应该可以帮助您打印当地时间和格林威治标准时间

  // gmt
  NSTimeZone *aTimeZone1 = [NSTimeZone localTimeZone];
  NSInteger aTimeInterval1 = -[aTimeZone1 secondsFromGMTForDate: [NSDate date]];
  NSLog(@"GMT: %@", [NSDate dateWithTimeInterval: aTimeInterval1 sinceDate: [NSDate date]]);

  // local
   NSTimeZone *aTimeZone2 = [NSTimeZone localTimeZone];
   NSInteger aTimeInterval2 = [aTimeZone2 secondsFromGMTForDate: [NSDate date]];
   NSLog(@"Local: %@", [NSDate dateWithTimeInterval: aTimeInterval2 sinceDate: [NSDate date]]);

如果你想使用 NSDateFormatter 那么试试这个怎么样:

  NSDateFormatter *aDateFormatter = [[NSDateFormatter alloc] init];
  [aDateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
  [aDateFormatter setDateFormat:@"dd:MM:yyyy HH:mm:ss"];
  NSLog(@"GMT: %@", [aDateFormatter stringFromDate:[NSDate date]]);

  [aDateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
  NSLog(@"Local: %@", [aDateFormatter stringFromDate:[NSDate date]]);

【讨论】:

    猜你喜欢
    • 2013-06-22
    • 1970-01-01
    • 2021-10-13
    • 2020-02-21
    • 2019-03-21
    • 2019-08-29
    • 2012-11-05
    • 2021-06-14
    相关资源
    最近更新 更多