0

I have two strings both are in following date format (2011-03-22).
i have to compare them and find number of days between them.

Can anyone tell me how to do this..

Please also tell me the correct method to convert them back to NSDate.

Kumar sonu
  • 535
  • 11
  • 24
  • 2
    possible duplicate of [How can I compare two dates, return a number of days.](http://stackoverflow.com/questions/2548008/how-can-i-compare-two-dates-return-a-number-of-days) – Vladimir Mar 23 '11 at 12:06

2 Answers2

2

Might be a couple of errors as i just typed this, but it speaks for itself and you should get the idea.

NSString *dateStringA = @"2011-03-22";

NSString *dateStringB = @"2011-03-27";

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = @"yyyy-MM-dd";

NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];

NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates


NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them
Zaky German
  • 14,324
  • 4
  • 25
  • 31
0

 For string to date

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];

for date to string

NSString *date = [[NSDate date] description];
Vaibhav Tekam
  • 2,344
  • 3
  • 18
  • 27