Objective c NSDate来自NSString
我已经阅读了DateFormatting指南,但仍然无法获得一个可用的格式化程序Objective c NSDate来自NSString,objective-c,iphone,nsdate,nsdateformatter,Objective C,Iphone,Nsdate,Nsdateformatter,我已经阅读了DateFormatting指南,但仍然无法获得一个可用的格式化程序 NSString *string = @"0901Z 12/17/09"; //This is a sample date. The Z stands for GMT timezone //The 0901 is 09h 01m on a 24 hour clock not 12. //As long as I can get the hours/min & date from the string
NSString *string = @"0901Z 12/17/09";
//This is a sample date. The Z stands for GMT timezone
//The 0901 is 09h 01m on a 24 hour clock not 12.
//As long as I can get the hours/min & date from the string I can deal with the time zone later
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"hhmm'Z' MM/dd/yy"];
NSDate *date = [dateFormat dateFromString:string];
当我尝试它时,它对我很有效。将
NSLog(@“%@”,date)
添加到您的代码末尾,可以得到以下输出:
2010-02-28 12:17:22.921 app[9204:a0f] 2009-12-17 09:01:00 -0800
你看到的问题是什么
编辑:我想出来了,你在09:01
上没有问题,但是在其他24小时的时间上,比如14:25
,对吗?将格式化程序更改为:
@"HHmm'Z' MM/dd/yy"
抄袭了我在这里回答的一个类似问题: 如果使用用户可见的日期,则应避免设置日期格式字符串。以这种方式格式化日期是不可本地化的,因此无法预测格式字符串在所有可能的用户配置中的表达方式。相反,您应该尝试限制自己设置日期和时间样式(通过-[NSDateFormatter setDateStyle:]和-[NSDateFormatter setTimeStyle:]) 另一方面,如果使用的是固定格式的日期,则应首先将日期格式化程序的区域设置设置为适合固定格式的内容。在大多数情况下,最好选择的语言环境是“en_US_POSIX”,这是一个专门设计的语言环境,无论用户和系统偏好如何,都能产生美国英语的结果。“en_US_POSIX”在时间上也是不变的(如果美国在将来的某个时候改变日期格式,“en_US”将改变以反映新的行为,但“en_US_POSIX”不会),在机器之间(“en_US_POSIX”在iPhone操作系统上的工作方式与在Mac OS X上的工作方式相同,在其他平台上的工作方式也一样) 一旦将“en_US_POSIX”设置为日期格式化程序的区域设置,就可以设置日期格式字符串,并且日期格式化程序将对所有用户保持一致的行为 以上信息和更多信息可以在苹果的 以下是我的应用程序中实现上述建议的代码片段:
static NSDateFormatter* dateFormatter = nil;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc]
initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
NSAssert(enUSPOSIXLocale != nil, @"POSIX may not be nil.");
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
dateFormatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss +0000";
}
显然是24小时的事情让我抓狂。谢谢