【问题标题】:NSDateFormatter string to date conversionNSDateFormatter 字符串到日期的转换
【发布时间】:2015-03-27 14:21:21
【问题描述】:

我需要转换

3/27/2015 5:45:00 AM

将字符串转换为 NSDate 对象。

我试过了;

[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];

但它不起作用。

我想不通的可能是什么问题?

谢谢

添加代码;

      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
      [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];  
      NSDate *tempDate = [dateFormatter dateFromString:@"3/27/2015 5:45:00 AM"]

编辑:

不知何故,因为时间片(AM/PM)为空。 我从 dateformatter 中删除了“a”,从字符串中删除了 AM。没关系。 但是还是不知道“a”有什么问题?

【问题讨论】:

  • 你试过“m/dd/yyyy h:mm:ss a”吗?据我所知,日期对数字敏感,您的月份只有一位数字,您应该使用 03/.. 05:..
  • 不起作用是什么意思?使用您的格式 [dateFromatter dateFromString:@"3/27/2015 5:45:00 AM"] 给我正确的输出。
  • @JakubVano 我没有得到正确的输入,我的日期为零
  • @erdemgc 你能发布给你错误结果的整个代码吗?
  • @JakubVano 我已经添加了代码,我已经编写了硬编码的字符串,但 tempDate 仍然为零

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

您忘记将日期区域设置的区域设置添加到日期格式化程序。 该代码将在任何设置为美国英语的设备上运行良好,但其他语言环境将失败。只需添加 en_US_POSIX 作为日期格式化程序的语言环境:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
NSDate *tempDate = [dateFormatter dateFromString:@"3/27/2015 5:45:00 AM"];

【讨论】:

    【解决方案2】:

    我不明白你的问题。

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
    NSDate *tempDate = [dateFormatter dateFromString:@"3/27/2015 5:45:00 AM"];
    NSLog(@"%@", tempDate); // prints "2015-03-27 09:45:00 +0000" to the console.
    

    这是您发布的代码。我逐字复制。我包含的NSLog 正确打印了日期,而不是nil

    【讨论】:

    • 当我复制并粘贴那段代码时,输​​出为 nil
    猜你喜欢
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多