0

I have start date and end date in string format.i want to compare end date and start date,end date should be greater than start date.How to do this.

NSLog(@"%@",date);
NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"dd MM yyyy"];

_start_date = [[NSDate alloc] init];

_start_date = [df dateFromString: date];

NSLog(@"date: %@", _start_date);`

Getting nil on start_date.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140

2 Answers2

0

Create an instance of NSDateFormatter. Configure it. Parse the strings to get NSDate objects (dateFromString:). Compare them (compare:).

Gabriel
  • 3,319
  • 1
  • 16
  • 21
0

You need to convert both the strings to NSDate objects using NSDateFormatter.

As your date is in dd-MM-yy format, do as shown below :

NSString *dateStr1 = @"21-3-14";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"dd-MM-yy"];
NSDate *date1 = [dateFormatter dateFromString:dateStr1];

Similarly create another date, say date2 Then you can compare these dates.

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");        

} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");

} else {
    NSLog(@"dates are the same");
}
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140