How to format NSDate?(如何格式化 NSDate?)
问题描述
如何让我的 NSDate 以例如2011 年 2 月 26 日星期二"的格式显示
How can I get my NSDate to display in the format for example i.e "Tue Feb 26, 2011"
推荐答案
做对了.不要对您的日期格式进行硬编码.有些国家不是您所在的国家/地区,它们可能有不同的日期格式.因此,如果您想向用户显示此日期,您应该使用一种将用户区域设置考虑在内的方法.
Do it right. Don't hardcode your date formats. There are countries that are not your country and they might have different date formats. So if you want to show this date to the user you should use a method that takes the users locale into account.
您可以使用 iOS4 中引入的 dateFormatFromTemplate:options:locale:
方法来获取包含您想要的所有信息的适当格式.
如果你必须支持 iOS <4 您应该使用此模板方法创建一个 plist,以便为用户区域设置创建正确的日期格式.
You could use the dateFormatFromTemplate:options:locale:
method introduced in iOS4 to get the appropriate format with all the information you want.
And if you have to support iOS < 4 you should create a plist with this template method to create the correct date format for the user locale.
NSLocale *locale = [NSLocale currentLocale];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"E MMM d yyyy" options:0 locale:locale];
[formatter setDateFormat:dateFormat];
[formatter setLocale:locale];
NSLog(@"Formatted date: %@", [formatter stringFromDate:myDate]);
为我的语言环境提供 So., 27. Feb 2011
.2011 年 2 月 27 日星期日
,适用于 en_US 语言环境
gives So., 27. Feb 2011
for my locale.
and Sun, Feb 27, 2011
for the en_US locale
这篇关于如何格式化 NSDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何格式化 NSDate?


基础教程推荐
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01