Tuesday, 18 June 2013

Date formatter in iOS (NSDateFormatter) OR Reset the date formatter


-(void)currentDateWithRequiredFormatter
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    
    // Current Date with default formatter..
    
    NSLog(@"Current Date with default Formatter = %@",[NSString stringWithFormat:@"%@",[NSDate date]]);
    
    // Set Date format as per your requirment..
    
    [formatter setDateFormat:@"dd/MM/yyyy"];
    
    // Set Current date to which you want...
    
    [formatter stringFromDate:[NSDate date]];
    
    NSLog(@"Current Date after using date Formatter = %@",[formatter stringFromDate:[NSDate date]]);
}

Out Put :

Current Date with default Formatter = 2013-06-19 04:43:35 +0000

Current Date after using date Formatter = 19/06/2013




// Second scenario
    
    // Suppose you have date as a string like..
     NSString* strGettingDate = @"24/05/2013";//dd/MM/yyyy
    
    NSLog(@"Without formatter : %@",strGettingDate);
    
    // And you want to 05.24.2013 // MM.dd.yyyy
    
    [formatter setDateFormat:@"MM.dd.yyyy"];
    [formatter dateFromString:strGettingDate];
    NSLog(@"Using date Formatter = %@",[formatter dateFromString:strGettingDate]);







Out Put :

Without formatter : 24/05/2013
Using after using date Formatter = (null)





 NSDateFormatter* formatter = [[NSDateFormatter alloc]init];

    // So solve this issue you have to set date format in which format you are getting first like..
    
    // Suppose you have date as a string like..
    NSString* strGettingDate = @"24/05/2013";//dd/MM/yyyy
    
     NSLog(@"Without formatter : %@",strGettingDate);
    
    [formatter setDateFormat:@"dd/MM/yyyy"];
    NSDate* dtDate = [formatter dateFromString:strGettingDate];
    
    // Now change the date format in which you want like..
    [formatter setDateFormat:@"MM.dd.yyyy"];
     NSString* strRequiredDate = [formatter stringFromDate:dtDate];
    
     NSLog(@"Using date Formatter : %@",strRequiredDate);

OUT PUT : 

 Without formatter : 24/05/2013
 Using date Formatter : 05.24.2013



You can also go for :
http://www.youtube.com/watch?v=p1FC9T7YdKI


No comments:

Post a Comment