【问题标题】:Create NSDate from 24h NSString return null从 24 小时创建 NSDate NSString 返回 null
【发布时间】:2015-05-23 13:20:57
【问题描述】:

我有NSString 这样的 24 小时格式:

NSString *a = @"10:00";
NSString *b = @"23:59";

我怎样才能用NSString b 获得NSDate

我使用:
+ setDateFormat: @"HH:mm" ==> 当手机设置为 24 小时时,它对 a 和 b 都有效。
+ setDateFormat: @"hh:mm" ==> 仅适用于手机设置为上午/下午。

我的完整代码,self.timeInit 是 24 小时格式的 NSString:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"HH:mm"];
    NSDate *date = [dateFormat dateFromString:self.timeInit];

    if (!date){
        [dateFormat setDateFormat:@"hh:mm"];
        date = [dateFormat dateFromString:self.timeInit];
        NSLog(@"Date 2: %@", date);
    }

    if (!date){
        [dateFormat setDateFormat:@"H:mm"];

        date = [dateFormat dateFromString:self.timeInit];
        NSLog(@"Date 3: %@", date);
    }

    NSLog(@"Date: %@", date);
    if (date){
        [self.timePickerUI setDate:date];
    }

【问题讨论】:

  • 我花了很多时间来测试和研究它。但我找不到解决方案。我尝试将“23:59”转换为“11:59 PM”,但 NSDate 仍然为空。
  • 我听不懂,你说:“setDateFormat:@"HH:mm" ==> 当手机设置为 24 小时时,它对 a 和 b 都有效。” => 你确实从字符串 b 中得到日期?那么你的问题是什么?
  • 当用户进入设置,将 24h 格式更改为 AM/PM 然后 NSDate 返回 null 时出现问题。
  • 你是如何得到字符串ab的?
  • 只是字符串,看我的编辑(完整代码)

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

您在 NSDateFormatter 上强制使用自己的语言环境,因此它会忽略用户的设置。

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"HH:mm"];
[dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *date = [dateFormat dateFromString:self.timeInit];

【讨论】:

  • 非常感谢,这是工作。我之前尝试过 setLocale,但 DateFormat 是错误的。因此,当 setLocale 时,NSDateFormatter 将覆盖用户的设置。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多