Sil*_*men 25 iphone time cocoa-touch nsdateformatter
我遇到了问题.我得到了12小时格式的传入时间字符串,我将它们转换为NSDate对象.当iPhone处于12小时格式时,没问题.但是当它采用24小时格式时,事情就出错了.以下是一些示例代码:
NSString *theTime = @"3:19 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"h:mm a"]; // "3:19 PM"
NSDate *date = [formatter dateFromString:theTime];
NSString *theString = [formatter stringFromDate:date];
Run Code Online (Sandbox Code Playgroud)
24小时模式,日期是1970-01-01三点19分00秒,而theString是"3:19" -错误
在12小时模式中,日期是1970-01-01 15:19:00,而弦是"下午3:19" - 右
所以...问题1:为什么设备的24小时设置会覆盖我的日期格式化程序设置?
更重要的是,问题2:如何从12小时到24小时进行正确的转换?
我已经有代码来检测手机是否处于24小时模式,但除了在字符串中挖掘并用15交换3之外,似乎没有干净的方法来执行此操作.
SVD*_*SVD 29
不确定你是否还需要它,但是我遇到了类似的问题,它通过设置日期格式化程序的语言环境得到了解决.也就是说,如果你想用它强制12小时模式,无论用户的24/12小时模式的设置,你应该将区域设置为en_US_POSIX.
Mee*_*eet 14
此行为的原因是Locale,设置正确的Locale
NSString *strAgendaDate = @"01/17/2012 12:00 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
[dateFormatter setDateFormat:AgendaDateFormatForMeeting];
NSDate *meetingDate = [dateFormatter dateFromString:aStrDate];
[dateFormatter setDateFormat:AgendaDateRepresentation];
strAgendaDate = [dateFormatter stringFromDate:meetingDate];
它适用于24小时和12小时格式
我相信@"h:mm a"应该是@"HH:mm a".
如果你在cocoa中使用pre-build dateformatter,那么一切都将为你完成.
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
Run Code Online (Sandbox Code Playgroud)
NSDateFormatterShortStyle并NSDateFormatterNoStyle有不同的品种.使用这些将确保您尊重用户为日期和时间选择的设置.
如果你有一个模型或一些值对象来存储你的日期,那么12-14小时时钟转换由SDK来处理NSDate.这样,只有在需要显示它们时才可以格式化它们.将日期保存为字符串可能会打开一个麻烦的世界,当您可以从单独指定GMT的xml解析它们或尝试添加和减去时NSTimeIntervals.
| 归档时间: |
|
| 查看次数: |
27548 次 |
| 最近记录: |