1
votes

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.

3

3 Answers

3
votes

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.

1
votes

Here are some formats for who desire to know!!

 12:16:45 PM on January 01, 2000   --> hh:mm:ss a 'on' MMMM dd, yyyy
 Wednesday, Sep 12, 2018           --> EEEE, MMM d, yyyy--
 09/12/2018                        --> MM/dd/yyyy--
 09-12-2018 14:11                  --> MM-dd-yyyy HH:mm--
 Sep 12, 2:11 PM                   --> MMM d, h:mm a--
 September 2018                    --> MMMM yyyy--
 Sep 12, 2018                      --> MMM d, yyyy
 Wed, 12 Sep 2018 14:11:54 +0000   --> E, d MMM yyyy HH:mm:ss Z
 2018-09-12T14:11:54+0000          --> yyyy-MM-dd'T'HH:mm:ssZ
 12.09.18                          --> dd.MM.yy
 10:41:02.112                      --> HH:mm:ss.SSS
 12:16:45 PM                       --> hh:mm:ss a
 AM or PM                          --> a
0
votes

NSDateFormatter uses date format patterns from UNICODE.

So for your 17 Nov 2010 date you need something like this:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"d MMM yyyy"];
NSString *result = [formatter stringForObjectValue:date];

Where date variable contains the date you'd like to format.

UPDATE: Try changing your code to this:

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