Difference between two NSDate objects — Result also a NSDate

后端 未结 5 1015
礼貌的吻别
礼貌的吻别 2020-11-30 20:38

I have two NSDate objects and I want the difference between the two and the result should again be a NSDate object. Any idea how to achieve this?

Here, I am trying t

5条回答
  •  情歌与酒
    2020-11-30 20:52

    NSDate represents an instance in time, so it doesn't make sense to represent an interval of time as an NSDate. What you want is NSDateComponents:

    NSDate *dateA;
    NSDate *dateB;
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
                                               fromDate:dateA
                                                 toDate:dateB
                                                options:0];
    
    NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
    

提交回复
热议问题