Formatting Date to dd-MMM in iOS

2019-05-23 22:18发布

问题:

I've been searching this and couldn't quite find it. I have an object in a NSDictionary that contains a NSDate. Now standard NSDate objects are pretty long. and I want to show the user in dd-MMM format.

For eg: The original date may be 2012-04-23 00:00:00 +0000, for which I want the date to appear as 23 Apr

I tried using NSDateComponents and NSDateFormatter but it didn't quite work. Probably I'm not figuring out the correct usage FOR the required format.

Here's the code for better understanding:

            NSLog(@"From Dictionary, Date = %@",[tmpDict objectForKey:@"eventDate"]);
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss Z"]; 
            NSString *dateString = [tmpDict objectForKey: @"eventDate"];
            NSDate *date = [dateFormatter dateFromString: dateString];

            NSLog(@"MY DATE: %@",date);
            NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
            [dateFormatter2 setDateFormat:@"dd-MMM"];
            NSString *formattedDateString = [dateFormatter2 stringFromDate:date];
            NSLog(@"Formatted Date: %@",formattedDateString);

The output is 2012-05-19 07:30:56 for From Dictionary, Date and null for Formatted Date and MY DATE. And tmpDict is the Dictionary Object that I'm using.

Thanks for the help, in advance.

回答1:

Following from Duncan C's answer.

If the date is represented as a string, first turn it into a date and then use the NSDateFormatter on it. Assuming the format will remain the same it would be

[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss Z"]; 
NSString *dateString = [dictionaryObject objectForKey: @"eventDate"];
NSDate *date = [dateFormatter dateFromString: dateString];

Then you can do what you are doing at the moment to the date object.



回答2:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MMM"];
NSString *formattedDateString = [dateFormatter stringFromDate:myDate];
[dateFormatter release];


回答3:

It sounds like the object you are fetching from your dictionary with the key eventDate is a string, not a date.

Try this code:

NSDate *myDate=[tmpDict objectForKey:@"eventDate"]; 
NSLog(@"myDate class = %@", [myDate class]);

I bet it shows a class of NSString or one of it's subclasses, not an NSDate.