Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of days between two NSDate objects

Tags:

ios

nsdate

I'm trying to compare two days of NSDate objects, I used at the first time NSDateComponents to calculate difference between my two dates Objects, but it is working correctly.

    NSString *dateStr =@"2012-11-05 15:00:00";
    NSDate *date = [dateFormat dateFromString:dateStr];
    NSDateComponents *datesDiff = [calendar components: NSDayCalendarUnit
                                              fromDate: date
                                                toDate: [NSDate date]
                                               options: 0];

That does not resolve my problem. Indeed when date1 = 2012-11-05 23:00:00 and date2 = 2012-11-06 10:00:00, the difference between the tow dates is 0 day and 11 hours. I am looking for something that allows me to detect day changes, in other words when date1 = 2012-11-05 23:00:00 and date2 = 2012-11-06 00:01:00, there's one day diffrence.

If someone knows the solution for that, i would welcome his suggestion. Thanks in advance

like image 938
Ali Avatar asked Nov 05 '12 16:11

Ali


2 Answers

I think you are looking for this (from the Date and Time Programming Guide):

Listing 13 Days between two dates, as the number of midnights between

@implementation NSCalendar (MySpecialCalculations)

-(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate
{
     NSInteger startDay=[self ordinalityOfUnit:NSDayCalendarUnit
          inUnit: NSEraCalendarUnit forDate:startDate];
     NSInteger endDay=[self ordinalityOfUnit:NSDayCalendarUnit
          inUnit: NSEraCalendarUnit forDate:endDate];
     return endDay-startDay;
}
@end

EDIT: Swift version:

extension NSCalendar {
    func daysWithinEraFromDate(startDate: NSDate, endDate: NSDate) -> Int {
        let startDay = self.ordinalityOfUnit(.Day, inUnit: NSCalendarUnit.Era, forDate: startDate)
        let endDay = self.ordinalityOfUnit(.Day, inUnit: NSCalendarUnit.Era, forDate: endDate)
        return endDay - startDay
    }
}
like image 127
Masa Avatar answered Oct 19 '22 07:10

Masa


NSString *start = @"2010-09-01";
NSString *end = @"2010-12-01";

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
[f release];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                    fromDate:startDate
                                                      toDate:endDate
                                                     options:0];
[gregorianCalendar release];

components now holds the difference.

NSLog(@"%ld", [components day]);
like image 32
Shekhar Gupta Avatar answered Oct 19 '22 06:10

Shekhar Gupta