【问题标题】:Converting 12 hour time NSString to 24 hour NSDate object does not work将 12 小时时间 NSString 转换为 24 小时 NSDate 对象不起作用
【发布时间】:2015-10-20 09:40:41
【问题描述】:

我需要将字符串(例如“12:00 AM”)转换为 24 小时格式的日期对象。 每当我运行以下代码来获取日期对象时,我都会得到 NULL。将语言环境更改为 en_US_POSIX 也不起作用。

NSString *TimeIn12hourFormat = @"12:00 am";
NSDateFormatter *timeFormatter = [NSDateFormatter new];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
[timeFormatter setLocale:[NSLocale currentLocale]];
[timeFormatter setDateFormat:@"HH:mm"];

NSDate  *dateIn24HourFormat = [timeFormatter dateFromString:TimeIn12hourFormat];
NSLog(@"Time in 24 hour format : %@", dateIn24HourFormat);

如果我做错了什么,请指出,否则请指导我如何做。我已经搜索了很多,关于这种字符串到日期的转换,但找不到这样的场景。 提前感谢任何帮助。

【问题讨论】:

  • 什么是输出?为什么要直接使用 NSLog() 而不是使用日期格式化程序来打印日期对象?您似乎不了解这里的重要区别。
  • 您的dateFormat 与您的字符串不匹配。 “HH”是 24 小时,也缺少如何阅读“am”。
  • 如果您稍后设置DateFormat,则设置TimeStyle en DateStyle 将无效,
  • @trojanfoe 我正在通过 NSLog() 打印它以检查控制台中的日期对象是否为空值。
  • 它肯定会这样做,但是一旦你开始让它工作,你会问我们为什么日期是your_timezone - GMT小时。

标签: ios objective-c nsstring nsdate nsdateformatter


【解决方案1】:

在您的 dateFormat 中添加一个字母“a”。这意味着,您的时间字符串末尾有“AM”。

[timeFormatter setDateFormat:@"hh:mm a"];

HH 是 24 小时制,hh 是上午/下午 12 小时制。

【讨论】:

  • 使用这个字母,也会在结果字符串中给出“AM”,这是不需要的。
【解决方案2】:

用下面的代码搞定了,感谢所有其他贡献者的帮助。

NSString *TimeIn12hourFormat = @"12:00 am";
NSDateFormatter *timeFormatter = [NSDateFormatter new];
[timeFormatter setDateFormat:@"hh:mm a"];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
[timeFormatter setLocale:[NSLocale currentLocale]];

NSDate  *dateIn24HourFormat = [timeFormatter dateFromString:TimeIn12hourFormat];
[timeFormatter setDateFormat:@"HH:mm"];

TimeIn12hourFormat          = [timeFormatter stringFromDate:dateIn24HourFormat];
NSLog(@"Time in 24 hour format : %@", TimeIn12hourFormat);

【讨论】:

    猜你喜欢
    • 2013-10-14
    • 2012-04-09
    • 1970-01-01
    • 2017-06-27
    • 2012-12-01
    • 2021-12-24
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多