Friday, June 24, 2011

Convert NSString to NSDate

This is helpful when say,

1. You want to compare 2 dates and your dates were stored as string , now in order to be able to compare them you have to convert them back to NSDate.

OR

2. You want to convert your Date String format so you want to convert your date string to date then user NSDateFormatter to display it in the required format.

You can do following:

       NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd-yyyy HH:mm "];
    NSDate* date = [formatter dateFromString:@"07-17-2012 15:20"];
    NSLog(@"%@", date); 
    // Note this prints date and time of another 
    //timezone because we didnt define it in our NSDateFormatter
    
    
    //Now convert it into another format
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"EEEE\n MMMM dd,yyyy HH:mm "];
    NSString *_strD=[formatter stringFromDate:date];
     NSLog(@"_strD=%@", _strD);



Original format of given date was 07-17-2012 15:20 and this code prints final date in following format:


Tuesday
July 17,2012 15:20 


On a different note, if you have 2 dates and you want to compare them you can use following:


    // Create date of your choice 
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd-yyyy HH:mm "];
    NSDate* date = [formatter dateFromString:@"07-17-2012 15:20"];    
    
    //Lets get today's date
    NSDate *today=[NSDate date];

    //compare today's date with the date of our choice
    NSInteger compareResult= [date compare:today];
    NSLog(@"compareResult=%d", compareResult);
    
    NSInteger compareResultMore= [today compare:date];
    NSLog(@"compareResultMore=%d", compareResultMore);


compareResult is = 1 if NSDate date  comes after NSDate today otherwise it will be -1.

No comments:

Post a Comment