0

I have a NSDate *da and when i print i get the following string : 2013-10-24 00:00:00 +0000.

NSDateFormatter *form = [[NSDateFormatter alloc] init];
[form setDateFormat:@"yyyy-mm-dd"];
NSDate *myD = [form dateFromString: @"2013-10-24"];

Now what i want to do is to compare NSDate *da and NSDate *myD. If it matches i need to print a NSLog.

if ([da isEqualToDate:myD]) {    
    NSLog(@"ok");               
} else {
    NSLog(@"bad");
}

The problem is that myD becomes null. How can i solve this?

UPDATE

Still there's a problem with the formatter; However now it doesn't return NIL.

When i print da i get the output 2013-10-24 13:00:00 +0000 and when i print myD i get the output 2013-10-23 18:30:00 +0000. Why didn't this get format correctly. I think there still exist some error in the formatting part of my code. Help

UPDATE 2

NSDate *da = [NSDate date]; ///// PRINTS 2013-09-16 11:52:40 +0000

    NSDateFormatter *form = [[NSDateFormatter alloc] init];
    [form setDateFormat:@"yyyy-MM-dd"];
    NSDate *myD = [form dateFromString: @"2013-09-16"]; ////// PRINTS 2013-09-16 00:00:00 +0000
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140

5 Answers5

1

Your format string is wrong as 'mm' stands for minutes, not months. Correct format will be

[form setDateFormat:@"yyyy-MM-dd"];
Vladimir
  • 170,431
  • 36
  • 387
  • 313
1

Month should be in uppercase:

[form setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter uses the specifications detailed here.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
0

You can change your dateformatter like

 [form setDateFormat:@"yyyy-MM-dd"];

and You can compare like this..

 NSTimeInterval daInterval = [da timeIntervalSince1970];
 NSTimeInterval myDInterval = [myD timeIntervalSince1970];

 if(daInterval == myDInterval)
    NSLog(@"dates are same..");
kalyani puvvada
  • 496
  • 4
  • 12
0

I think the problem you have is that you are not doing this:

[form setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

And you create a time in different timezone and than it gets formatted to your local timezone while printing.

Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71
0
    NSString *str1=@"2013-10-24 00:00:00 +0000";
    NSDateFormatter *form = [[NSDateFormatter alloc] init];
    [form setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    NSDate *date1= [form dateFromString:str1];
    NSLog(@"%@",date1);


    NSString *str2=@"2013-10-24 00:00:00 +0000";
    NSDate *date2= [form dateFromString:str2];

   if ([date1 isEqualToDate:date2]) {
      NSLog(@"Same");
   }
   else
   {
      NSLog(@"Not Same");
  }

i hope it is useful..

Developer
  • 760
  • 3
  • 15