Number of Days Between Two Nsdates

Number of days between two NSDates

Here's an implementation I used to determine the number of calendar days between two dates:

+ (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];
}

EDIT:

Fantastic solution above, here's Swift version below as an extension on NSDate:

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
}
}

A bit of force unwrapping going on which you may want to remove depending on your use case.

The above solution also works for time zones other than the current time zone, perfect for an app that shows information about places all around the world.

Swift days between two NSDates

You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00 and 2015-01-02 09:00, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).

If your purpose is to get the exact day number between two dates, you can work around this issue like this:

// Assuming that firstDate and secondDate are defined
// ...

let calendar = NSCalendar.currentCalendar()

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)

let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: [])

components.day // This will return the number of day(s) between dates

Swift 3 and Swift 4 Version

let calendar = Calendar.current

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)

let components = calendar.dateComponents([.day], from: date1, to: date2)

How to get number of days between two dates objective-c

By default [NSDate date] return date in like 2013-08-06 08:50:25 +0000
and you have set your formatter to yyyy-MM-dd this, so you have to convert your startDate to yyyy-MM-dd this form..

Try this

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-ddHH:mm:ss ZZZ"];
NSDate *startDate = [NSDate date];
NSLog(@"%@",startDate);
NSDate *endDate = [f dateFromString:end];
NSLog(@"%@",endDate);


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

Number of Months and Days between two NSDates

As Hot Licks correctly said, you can't convert a number of days to months/days in most calendars.

However, the NSCalendar method components:fromDate:toDate:options: can do this calculation if you agree with Apple's implementation. From the documentation:

The result is lossy if there is not a small enough unit requested to hold the full precision of the difference. Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days.

The discussion in the documentation even includes sample code for exactly your problem:

NSDate *startDate = ...;
NSDate *endDate = ...;
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
int months = [comps month];
int days = [comps day];

How can i calculate the days between two dates?

Try this code, updated for Swift 2.0

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let first = "2010-09-01"
let firstDate = dateFormatter.dateFromString(first)!
let last = "2010-09-05"
let lastDate = dateFormatter.dateFromString(last)!

let currentCalendar = NSCalendar.currentCalendar()
let timeUnitDay = NSCalendarUnit.Day

let daysBetween = currentCalendar.components(timeUnitDay, fromDate: firstDate, toDate: lastDate, options: NSCalendarOptions.MatchStrictly)

print(daysBetween.day)

Calculating the number of days between two dates in Objective-C

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];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:startDate
toDate:endDate
options:0];

components now holds the difference.

NSLog(@"%ld", [components day]);


Related Topics



Leave a reply



Submit