【问题标题】:NSDateComponents not printing accurate day/month/year times [duplicate]NSDateComponents没有打印准确的日/月/年时间[重复]
【发布时间】:2018-05-16 19:44:43
【问题描述】:

我正在使用 NSDateComponents 分别获取每一天、月、年、小时、分钟等,但日、月、年和秒在 2017-11-08 1:00:00 时不准确......有人知道我错过了什么吗?

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
        NSDate *date = [dateFormatter dateFromString:@"2017-11-08 1:00:00"];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
        NSInteger day = [components day];
        NSInteger month = [components month];
        NSInteger year = [components year];
        NSInteger hour = [components hour];
        NSInteger minute = [components minute];
        NSInteger second = [components second];
        NSLog(@"day: %ld",(long)day);
        NSLog(@"month: %ld",(long)month);
        NSLog(@"year: %ld",(long)year);
        NSLog(@"hour: %ld",(long)hour);
        NSLog(@"minute: %ld",(long)minute);
        NSLog(@"second: %ld",(long)second);

输出:

        day: 2147483647
        month: 2147483647
        year: 2147483647
        hour: 1
        minute: 0
        second: 2147483647

【问题讨论】:

    标签: objective-c nsdatecomponents


    【解决方案1】:

    你只得到小时和分钟,因为这就是你所要求的。如果你真的要求日、月、年和秒,你会得到它们:

    NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear |
                           NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *components = [calendar components:units fromDate:date];
    

    【讨论】:

      猜你喜欢
      • 2021-01-01
      • 2019-12-12
      • 2018-02-06
      • 1970-01-01
      • 2013-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多