【问题标题】:NSDateFormatter in 12-hour mode12 小时模式下的 NSDateFormatter
【发布时间】:2012-06-16 09:29:44
【问题描述】:

我有以下代码。

NSDateFormatter *df = ...;
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
NSDate * date = [df dateFromString:date_string]; //here is the problem

在 24 小时模式下,一切正常。在设备上设置 12 小时模式时,stringFromDate 返回 null。 date_string 的格式一直都是一样的,日期格式也是一样的。为什么会这样?

【问题讨论】:

  • 你能显示 date_string 的值吗!
  • 2012-06-16T10:00:47.436+0000 例如
  • this post

标签: objective-c ios datetime nsdate nsdateformatter


【解决方案1】:

在你的NSDateFormatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"HH 代表 24 小时,hh 代表 12 小时

【讨论】:

  • 我想忽略12小时系统设置,不知道怎么办
  • @Sergey 然后使用 hh 而不是 HH
  • 这不是真的。如果用户关闭了 24 小时并使用 HH,它仍然是 12 小时格式。
  • 如果您想添加 AM / PM,请在格式字符串的末尾添加字母“a”,如下所示:“hh:mm a”
【解决方案2】:

尝试以这种方式设置语言环境:

NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
df.locale = twelveHourLocale;

要强制改为 24 小时,您可以使用:

NSLocale *twentyFour = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];

【讨论】:

  • 我想强制 dateformatter 忽略 12 小时模式并一直使用 24 小时。我应该使用什么 loc 标识符?
  • en_GB --> NSLocale* formatterLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease];
  • 太棒了!像魅力一样工作。
  • 不推荐。 “hh”表示 12 小时,“HH”表示 24 小时
【解决方案3】:

12 小时制到 24 小时制:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSDate *amPmDate = [formatter dateFromString:amPmHourString];
[formatter setDateFormat:@"HH:mm"];
NSString *24HourString = [formatter stringFromDate:amPmDate]];

24 小时模式到 12 小时模式正好相反

【讨论】:

    【解决方案4】:
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    NSLocale *locale = [[[NSLocale alloc] 
                    initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];  
    [dateFormat setLocale:locale];
    

    【讨论】:

      猜你喜欢
      • 2013-09-01
      • 2011-11-16
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多