Wednesday, August 8, 2012

Few tips on NSDate

Formatting Current NSDate

 NSDate *today = [NSDate date];
 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   [formatter setDateFormat:@"MM/dd/yyyy"];
 NSString *fromDateString=[formatter stringFromDate:today];
   NSLog(@"Current Date  : %@",fromDateString); 

 Sorting array of NSDate

NSArray *timeArray = [NSArray arrayWithObjects:@"07/27/2012",@"08/29/2012",@"05/30/2012",@"04/01/2012",@"07/27/2013", @"07/27/2011",nil];
 NSMutableArray *testArray = [[NSMutableArray alloc]initWithObjects:nil, nil];
 

    for (int i =0 ; i<[timeArray count]; i++) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // this is imporant - we set our input date format to match our input string
        // if format doesn't match you'll get nil from your string and app will crash, so be careful

        [dateFormatter setDateFormat:@"MM/dd/yyyy"];
          // create nsdate object from nsstring
        NSDate *dateFromString = [dateFormatter dateFromString:[timeArray objectAtIndex:i]];
        [testArray addObject:dateFromString];
    }
    NSArray *sortedArray = [[[NSArray alloc]initWithArray:testArray] sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"Filtered Array : %@",sortedArray);


Comparing two NSDate

     NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
   
    dt1 = [df dateFromString:@"2012-08-09"];
    dt2 = [df dateFromString:@"2012-07-19"];
   
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result) {
        case NSOrderedAscending:
            NSLog(@"%@ is greater than %@",dt2,dt1);
            break;
        case NSOrderedDescending:
            NSLog(@"%@ is less than %@",dt2,dt1);
            break;
        case NSOrderedSame:
            NSLog(@"%@ is equal to %@",dt2,dt1);
            break;

        default:
             NSLog(@"error dates : %@ ,%@",dt2,dt1);
            break;
    }

1 comment:

  1. very useful for beginners .. keep spreading your knowledge guyz

    ReplyDelete