-1

I want to compare two dates.For that i have to dates in two strings(fromDates and toDates).

here fromDate is showing the correct value in console.

//Console.
19/12/2012 from date is

After the NSDateFormatter process im getting wrong format and date and sometime it is showing NULL.

//console
First = (null)

I used the below method.

if (fromDate) {
        self.printFromDate.text = [NSString stringWithFormat:@"%@",curBtn.dateString];
        fromDates = self.printFromDate.text;
        NSLog(@"%@ from date is",fromDates);
       dtFormatter  = [[NSDateFormatter alloc] init];
        [dtFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *strDate = [dtFormatter dateFromString:fromDates];
        NSLog(@"First = %@",strDate);    
    }

Can anyone please tell me where im goin wrong.i completly stuck here.Thanks in advance.

suji
  • 1,470
  • 6
  • 22
  • 41

2 Answers2

3

Your date formatter doesn't follow the string format.

I think you're looking for this:

[dtFormatter setDateFormat:@"dd/MM/yyyy"];
NSDate *date1 = [dtFormatter dateFromString:fromDates];
NSDate *date2 = [dtFormatter dateFromString:anotherDate];

if ([date1 compare:date2] == NSOrderedDescending)
    NSLog(@"date1 comes first");        
else if ([date1 compare:date2] == NSOrderedAscending)
    NSLog(@"date2 comes first");
else
    NSLog(@"date1 is the same date as date2");
John
  • 2,675
  • 2
  • 18
  • 19
  • you are correct.now it is showing like this First = 2012-12-28 00:00:00 +0000 – suji Dec 03 '12 at 08:19
  • if suppose i want in this format 28/12/2012,how to set it.can you please help me – suji Dec 03 '12 at 08:20
  • That is the the `description` format of an NSDate. To convert it back to an NSString, you can use the same formatter and `[dtFormatter stringFromDate:date]` – John Dec 03 '12 at 08:21
  • But at that point, what is the point of using a date formatter? – John Dec 03 '12 at 08:22
  • i wnat to compare two dates.thats all. – suji Dec 03 '12 at 08:23
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/20504/discussion-between-suji-and-john) – suji Dec 03 '12 at 08:24
1
        dtFormatter  = [[NSDateFormatter alloc] init];
        [dtFormatter setDateFormat:@"dd/MM/yyyy"];
        NSDate *strDate = [[NSDate alloc] init];
        strDate = [dtFormatter dateFromString:fromDates];
        NSLog(@"First = %@",strDate); 

I think it will be helpful to you.

Prasad G
  • 6,702
  • 7
  • 42
  • 65