0

Possible Duplicate:
iPhone - get number of days between two dates

I am trying to compare 2 dates and find out the number of day in between them.

something like below:

now = [NSDate date];

// This is i am saving in NSUSerdefault on some condition,like 

if (a == 1) {

    dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:MM:SS";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSLog(@"The Current Time is %@",[dateFormatter stringFromDate:now]);
    datesaved = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:now]];
    NSLog(@"old date saved : %@",datesaved);

    [dateFormatter release];
}

and find current date .

Now i want to compare current date with the date saved in NSUserDefaults to find number of day in between them.

ex:

The Current Time is 2012-12-16 19:12:74 old date saved : 2012-12-12 19:12:74

Number of days : 4

Thanks

Community
  • 1
  • 1
Shishir.bobby
  • 10,994
  • 21
  • 71
  • 100
  • By the way, the HH:MM:SS should probably be HH:mm:ss. MM is grabbing the month! And, looking at your example, SS gives the fractional second (74 in your example!), not the number of seconds. See [date format patterns](http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns). – Rob Dec 16 '12 at 14:53
  • pow(duplicate,09823984712947) times these NSdate questions are there. I would suggest to make NSDateOverflow... :p – Anoop Vaidya Dec 16 '12 at 16:22

2 Answers2

1
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);
jsteinmann
  • 4,502
  • 3
  • 17
  • 21
  • 1
    This tells you the number of 24 hour periods and not days. What if it is from 10pm to 2am? One day has passed, but only 4 hours. – lnafziger Dec 16 '12 at 14:50
  • note, that due to daylight saving times and leap seconds a day's length can vary between 82440 and 90001 seconds. – vikingosegundo Dec 16 '12 at 16:39
1

You can take the day component of a date this way:

NSDate* now = [NSDate date]; // Or date from format
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* components = [cal components: NSDayCalendarUnit fromDate: now];
NSInteger day = [components day];

Do the same for the other date and compare them.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187