Formatting Date to dd-MMM in iOS

泄露秘密 提交于 2019-12-10 11:13:36

问题


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.



来源:https://stackoverflow.com/questions/10574248/formatting-date-to-dd-mmm-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!