【发布时间】:2011-02-18 12:55:28
【问题描述】:
我想知道Friday, December 18th 是哪种日期格式,也是这种标准日期格式,否则我必须付出一些努力才能得到它。
谢谢。
【问题讨论】:
标签: iphone objective-c nsdate nsdateformatter
我想知道Friday, December 18th 是哪种日期格式,也是这种标准日期格式,否则我必须付出一些努力才能得到它。
谢谢。
【问题讨论】:
标签: iphone objective-c nsdate nsdateformatter
我认为 th 不可能通过格式化程序实现。虽然你可以这样做:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE, MMMM d"];
NSString *dateString = [dateFormat stringFromDate:today];
NSCalendar *cal = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *dtComp = [cal components:unitFlags fromDate:today];
switch ([dtComp day]) {
case 1:
case 31:
case 21:
dateString = [dateString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i",[dtComp day]] withString:[NSString stringWithFormat:@"%ist",[dtComp day]]];
break;
case 2:
case 22:
dateString = [dateString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i",[dtComp day]] withString:[NSString stringWithFormat:@"%ind",[dtComp day]]];
break;
case 3:
case 23:
dateString = [dateString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i",[dtComp day]] withString:[NSString stringWithFormat:@"%ird",[dtComp day]]];
break;
default:
dateString = [dateString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i",[dtComp day]] withString:[NSString stringWithFormat:@"%ith",[dtComp day]]];
break;
}
[dateFormat release];
【讨论】:
@Robin Help with NSDateFormatter 在NSDateFormatter 这种情况下对你有很大帮助,你真的必须努力工作才能获得这种格式,看看我与你分享的链接。
祝你好运!
【讨论】:
如果可以以可读的方式发布长 cmets,我会评论 Madhups 的答案。
这是我的评论:
这些自定义日期格式的坏处是,如果您不是来自美国或其他使用相同日期格式的国家/地区,则日期是错误的。
这是您的解决方案在我的设备上的外观:Freitag,2 月 18 日
我妈妈会说th?这是什么意思?
我会说“另一个从未离开过他的国家的开发者。”
请我想要这样的约会:Freitag,2 月 18 日
因为这是我习惯的。这就是约会的样子。
因此,如果当前语言环境与您使用的自定义日期格式相似,请添加仅使用自定义日期格式器的检查。
Apple 在 iOS4 中引入了一个非常酷的方法。
+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale
你将这个方法传递给你想要在你的日期格式中的每个组件,你会得到一个使用区域设置的格式。
因此,如果您想使用工作日、日期和月份,您可以使用以下内容:
NSString *localizedDateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE MMMM d" options:0 locale:[NSLocale currentLocale]];
对于德语语言环境,它将返回 EEEE, d. MMMM。或 EEEE, MMMM d 用于美国语言环境。然后,您可以使用它来设置自定义 dateFormat。
这就是 NSDateFormatter 的全部意义所在。本地化日期。如果您使用[dateFormatter setDateFormat:@"some hard coded date format"] 向用户显示日期,则在大多数情况下您做错了。
我真的很讨厌混合美国日期风格和德国日期风格的应用程序。
【讨论】: