Search code examples
iphoneobjective-cios4nsdatensdateformatter

How to convert date string into format "17 Nov 2010"


I have the date that is in format 2010-11-17.This is of the form NSString.

I want to convert this NSString date into format 17 Nov 2010 and display in a label

This date is just not the current date but may even be the older dates.

So I cant use the [NSDate date] instance to get the date.

I tried using NSDateFormatter with the method dateFromString.

But it gives me a null value.

Here is the code snippet

NSString *dates  = @”2010-11-16”;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MMM yyyy"];
NSDate *dates1 = [dateFormatter dateFromString:dates];
NSString *dates2 = [dateFormatter stringForObjectValue:dates1];
NSLog(@"dates : %@",dates);
NSLog(@"Dates 2 :  %@",dates2);
[dateLabel setText:dates2];
NSLog(@"Formatted Date is : %@",dateLabel.text);

What should be done?

Please Help and suggest.

Thanks.


Solution

  • Try this

    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd"];
    NSDate *date2 = [formater dateFromString:@"2010-11-17"];
    [formater setDateFormat:@"d MMM yyyy"];
    NSString *result = [formater stringFromDate:date2];
    NSLog(@"RESULT %@",result);
    

    I got the result.Correct me if this approach is wrong.