在iOS中将日期格式化为dd-MMM [英] Formatting Date to dd-MMM in iOS
问题描述
我一直在搜索,但找不到.我在包含NSDate的NSDictionary中有一个对象.现在,标准的NSDate对象相当长.我想以dd-MMM格式显示用户.
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.
例如:原始日期可能是2012-04-23 00:00:00 +0000
,我希望该日期显示为23 Apr
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
我尝试使用NSDateComponents和NSDateFormatter,但效果不佳.可能我没有弄清楚所需格式的正确用法.
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);
对于From Dictionary, Date
,输出为2012-05-19 07:30:56,对于格式化日期"和我的日期",输出为null. tmpDict
是我正在使用的Dictionary对象.
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.
感谢您的帮助.
推荐答案
来自 Duncan C 的答案
如果日期表示为字符串,请首先将其转换为日期,然后在其上使用NSDateFormatter.假设格式将保持不变
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];
然后,您可以对date
对象执行当前操作.
Then you can do what you are doing at the moment to the date
object.
这篇关于在iOS中将日期格式化为dd-MMM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!