【问题标题】:How can I Convert a NSString to a valid NSDate (iOS)如何将 NSString 转换为有效的 NSDate (iOS)
【发布时间】:2012-02-17 14:57:38
【问题描述】:

我以“2012-02-17 14:21:30 +0000”的形式将一个字符串从 javascript 传递到 Objective-C。 我的代码如下:

NSString *firingDate = [_parameters objectForKey:@"fire"];
NSDate *notificationDate = [NSDate dateWithString:firingDate];

问题是我最终阅读了 OS X 参考而不是 iOS 文档(doh!),因此这会引发警告,因为 iOS 中不存在 dateWithString。从理论上讲,我认为这根本不应该起作用,但它确实有效,尽管有那个警告。

将字符串转换为 NSDate 的正确方法是什么?

【问题讨论】:

标签: objective-c ios nsstring nsdate


【解决方案1】:

正确的方法是使用NSDateFormatter 作为工厂从字符串创建日期(反之亦然)。

【讨论】:

    【解决方案2】:

    试试:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss Z";
    NSDate *notificationDate = [formatter dateFromString:firingDate];
    

    【讨论】:

    • 我认为日期格式应该是“YYYY-MM-dd HH:mm:ss Z”(这对我有用)
    【解决方案3】:

    试试这个:

    NSString *firingDate = [_parameters objectForKey:@"fire"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSDate *notificationDate = [dateFormatter dateFromString:firingDate];
    

    查看reference 以解析来自多个区域的日期。

    完成后不要忘记释放格式化程序。

    【讨论】:

      猜你喜欢
      • 2014-12-10
      • 2015-08-01
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 2011-04-24
      • 2017-04-23
      相关资源
      最近更新 更多