Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
How can I compare two dates, return a number of days

I have two dates (as NSString in the form "yyyy-mm-dd"), for example:

NSString *start = "2010-11-01"; NSString *end = "2010-12-01"; 

I'd like to implement:

- (int)numberOfDaysBetween:(NSString *)startDate and:(NSString *)endDate {  } 
like image 312
CodeGuy Avatar asked Jan 01 '11 20:01

CodeGuy


People also ask

How do I get the difference between two dates in Objective C?

NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"]; NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"]; NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1]; int numberOfDays = secondsBetween / 86400; NSLog(@"There are %d days in between the two dates.", numberOfDays);

How do I calculate the number of days between two dates?

To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.

How can I get the difference between two dates in IOS?

Getting difference between two dates is easy. You should know how to play between the dates. We will be using DateFormatter class for formatting the dates. Instances of DateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.

How do I calculate the number of days between two dates in C++?

Number of days = monthDays[date[1]]. monthDays will store the total number of days till the 1st date of the month.


1 Answers

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]); 
like image 83
vikingosegundo Avatar answered Sep 23 '22 01:09

vikingosegundo