NSDateFormatter dateFromString和iPhone 24小时格式混淆

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.

  • 一个不那么明显的结论:让系统的语言环境通过一个普通的`[[NSDateFormatter alloc] init]`创建的日期格式化程序.将此格式化程序用于您向用户显示的任何字符串.如果你想从一个总是12或24小时的源(比如一个app const或服务器)获取一个字符串,在另一个格式化程序上使用`.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]`确保他们没有受到虐待.只要记住日期格式化程序控制12/24小时的时间表达,而且`NSDate不会,并且事情会好起来的. (3认同)

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小时格式


Ric*_*kiG 6

我相信@"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)

NSDateFormatterShortStyleNSDateFormatterNoStyle有不同的品种.使用这些将确保您尊重用户为日期和时间选择的设置.

如果你有一个模型或一些值对象来存储你的日期,那么12-14小时时钟转换由SDK来处理NSDate.这样,只有在需要显示它们时才可以格式化它们.将日期保存为字符串可能会打开一个麻烦的世界,当您可以从单独指定GMT的xml解析它们或尝试添加和减去时NSTimeIntervals.


Vla*_*mir 6

我从@"hh:mm:ss"变为@"HH:mm:ss",时间风格从" 1:03 PM "变为" 13:03 ".希望这会帮助你.