Search code examples
iosobjective-cnsdate

NSDate gave the wrong answer (Objective-C)


I want transfer second to Hour and minute , and I don't care the Date. but the codes below gave me a wrong result. I passed "7879"second and it should be converse to '02:11:19' , But it returns 10:11:20 . I don't know Where goes wrong.

enter image description here p.s. I noticed that the d-value is 8hours so I think it's about the timeZone.. but as I add the code formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"]; it returned me the same result.


Solution

  • Use NSDateComponentsFormatter.

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

    output:

    2:11:19
    

    Swift 3 version

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