Reputation: 1934
How can I tell the amount of days from now until the date specified in my app? Here is what I have so far, but it comes up with "-30" every time, no matter what the date is:
NSDate * selected = [DatePicker date];
NSString * date = [selected description];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
fromDate:DatePicker.date];
CalLabel1.text = [NSString stringWithFormat:@"%d", [components day]];
NSDateFormatter *temp = [[NSDateFormatter alloc] init];
[temp setDateFormat:@"dd/MM/yyyy"];
NSDate *stDt = [temp dateFromString:[temp stringFromDate:[NSDate date]]];
NSDate *endDt = [temp dateFromString:[temp stringFromDate:[NSString stringWithFormat:@"%d", [components date]]]];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt toDate:endDt options:0];
int days = [comps day];
NSLog(@"%i", [comps day]);
Upvotes: 3
Views: 2113
Reputation: 1755
Swift 3 version of the accepted answer.
let dateComponents = Calendar.current.dateComponents([.day], from: fromDate, to: Date())
// number of days is an optional Int
if let daysCount = dateComponents.day {
print(daysCount)
}
Upvotes: 1
Reputation:
NSDate * selected = [DatePicker date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components: NSDayCalendarUnit
fromDate: [NSDate date]
toDate: selected
options: 0];
int days = [comps day];
NSLog(@"%i", [comps day]);
This calculates the number of days between now and the selected date. All your messing around with the date formatter was wrong and not necessary.
Upvotes: 7
Reputation: 30846
What about just using -timeIntervalSinceNow
on NSDate
?
NSDate *selectedDate = [datePicker date];
NSTimeInterval numberOfSecondsUntilSelectedDate = [selectedDate timeIntervalSinceNow];
NSInteger numberOfDays = numberOfSecondsUntilSelectedDate / 86400; // 86,400 seconds in a day
Upvotes: 3