Calculate total number of weeks from two NSDate

978 views Asked by At

I want to check if the current NSDate is 2 Weeks ahead of the another NSDate. I have can do somethings as below code but was wondering if there is any proper way to do.

[calendar rangeOfUnit:NSCalendarUnitDay startDate:&currentDate interval:NULL forDate:currentDate];

[calendar rangeOfUnit:NSCalendarUnitDay startDate:&previousDate interval:NULL forDate:previousDate];

NSDateComponents *difference = [calendar components:NSCalendarUnitDay fromDate:previousDate toDate:currentDate options:0];

if(diiference >= 14) { 

}
2

There are 2 answers

3
Pushkraj Lanjekar On

You can use one trick here. First calculate number of days between 2 dates and then calculate number of weeks between them. You can do it like

-(NSInteger)weeksBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime {
    NSDate *fromDate;
    NSDate *toDate;

    NSCalendar *calendar = [NSCalendar currentCalendar];

    [calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
                 interval:NULL forDate:fromDateTime];
    [calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
                 interval:NULL forDate:toDateTime];

    NSDateComponents *difference = [calendar components:NSCalendarUnitDay
                                               fromDate:fromDate toDate:toDate options:0];

    return [difference day] / 7;
}

You can use CGFloat if you want to get week value like 1.5 and keep as it is if you want week count like 1,2,3,etc

0
Dishant Rajput On

Try this

objective C

+ (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime
{
NSDate *fromDate;
NSDate *toDate;

NSCalendar *calendar = [NSCalendar currentCalendar];

[calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
    interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
    interval:NULL forDate:toDateTime];

NSDateComponents *difference = [calendar components:NSCalendarUnitDay
    fromDate:fromDate toDate:toDate options:0];

return [difference day];
}

Swift

extension NSDate {
func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -> Int {
let calendar = NSCalendar.currentCalendar()
if let timeZone = timeZone {
  calendar.timeZone = timeZone
}

var fromDate: NSDate?, toDate: NSDate?

calendar.rangeOfUnit(.Day, startDate: &fromDate, interval: nil, forDate: self)
calendar.rangeOfUnit(.Day, startDate: &toDate, interval: nil, forDate: toDateTime)

let difference = calendar.components(.Day, fromDate: fromDate!, toDate: toDate!, options: [])
return difference.day
}
}