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 { }
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);
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.
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.
Number of days = monthDays[date[1]]. monthDays will store the total number of days till the 1st date of the month.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With