【问题标题】:NSDate gave the wrong answer (Objective-C)NSDate 给出了错误的答案(Objective-C)
【发布时间】:2017-08-02 06:07:44
【问题描述】:

我想将秒转移到小时和分钟,我不在乎日期。但下面的代码给了我一个错误的结果。我第二次通过了 "7879" ,它应该与 '02:11:19' 相反,但它返回 10:11:20 。不知道哪里出了问题。

p.s.我注意到 d 值是 8 小时,所以我认为它与时区有关。但是当我添加代码 formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"]; 时,它返回了相同的结果。

【问题讨论】:

  • 试试NSDate *date = [NSDate date]; 看看是否仍然得到错误的结果?
  • 添加代码以便我们跟踪问题。
  • 时间戳到底是什么?这是从哪个日期/小时开始的秒数?
  • 您需要在 GMT 工作。而不是这个:formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];使用这个:formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

标签: ios objective-c nsdate


【解决方案1】:

使用 NSDateComponentsFormatter。

NSDateComponentsFormatter *dateComponentsFormatter = [[NSDateComponentsFormatter alloc] init];
dateComponentsFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
dateComponentsFormatter.allowedUnits = (NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond);
NSLog(@"%@", [dateComponentsFormatter stringFromTimeInterval:7879]);

输出:

2:11:19

Swift 3 版本

let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.zeroFormattingBehavior = .pad
dateComponentsFormatter.allowedUnits = ([.hour, .minute, .second])
print("\(String(describing: dateComponentsFormatter.string(from: 7879)))")

【讨论】:

    猜你喜欢
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多