Saturday, 19 May 2012

how to compare two dates with using NSUserDefaults in iphone sdk

 NSDateFormatter *df= [[NSDateFormatter alloc] init];
   
    [df setDateFormat:@"yyyy-MM-dd"];
   
    NSDate *dt1 = [[NSDate alloc] init];
   
    dt1=[df dateFromString:@"2012-06-25"];
   
   
    [[NSUserDefaults standardUserDefaults] setObject:dt1 forKey:@"myDateKey"];
  

    NSDate *myDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"myDateKey"];
    NSLog(@"%@",myDate);
   
    NSDate *currDate = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd/MM/yyyy"];

   
    NSLog(@"%@",currDate);
   
    NSComparisonResult result = [currDate compare:myDate];
   
    switch (result)
   
    {
           
        case NSOrderedAscending:
            NSLog(@"%@ is greater than %@", myDate, currDate);
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"%@ is greater than %@" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
            break;
           
        case NSOrderedDescending:
            NSLog(@"%@ is less %@", myDate, currDate);
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"%@ is less than %@" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert1 show];
            [alert1 release];
            break;
           
        case NSOrderedSame:
            NSLog(@"%@ is equal to %@", myDate, currDate);
            UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"%@ is equal to %@" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert2 show];
            [alert2 release];
            break;
         
           
        default:
            NSLog(@"erorr dates %@, %@", myDate, currDate);
            UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"error dates %@, %@" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert3 show];
            [alert3 release];
            break;
    }

No comments:

Post a Comment