【问题标题】:Converting NSString to NSdate将 NSString 转换为 NSdate
【发布时间】:2017-04-23 22:37:54
【问题描述】:

我想将 NSString 转换为 NSDate。

问题是我正在从给出 NSString 值的图像中读取 exif 信息。 现在我想将此 NSString 转换为 NSDate

下面我试过了

      NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:&error];
      NSArray *matches = [detector matchesInString:datestring
                                     options:0
                                       range:NSMakeRange(0, [datestring length])];


    for (NSTextCheckingResult *match in matches) {
       if ([match resultType] == NSTextCheckingTypeDate) {
           dateObj =  [match date];
           break;
    }
}

=================

我在 exif 中看到的格式是 2010:05:27 17:48:42+04:00

注意:- 是否有任何方法可以采用任何 NSString 格式并给出 NSDate 对象

编辑

在 NSDateformatter 中,我们必须传递给定的格式类型。我们能否有一种方法可以在运行时从字符串中确定日期格式,因为字符串可能具有不同的格式,具体取决于本地化或相机类型。

【问题讨论】:

  • 您需要NSDateFormatter,而不是NSDataDetector。 Stack Overflow 上大约有一半关于 iOS 的问题是关于解析日期的问题,你应该很容易找到。

标签: ios objective-c nsstring nsdate


【解决方案1】:

正如@Cyrille 所说,你必须使用NSDateFormatter

NSString *myString = @"2010:05:27 17:48:42+0400";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ssZZZ"];

NSDate *myDate = [dateFormatter dateFromString:myString];

【讨论】:

    【解决方案2】:

    我认为最好的办法是创建一个仅用于处理日期的类,所以我更喜欢使用 NSDateForamatter 创建一个类似的方法:

    + (NSDate *)getDateFromStringDate:(NSString *)stringDate {
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"];
        return [dateFormat dateFromString:stringDate]; 
    }
    

    在那里你可以设置你拥有的日期格式。 希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      NSDateFormatter: 是将NSString 转换为NSDate 的最佳方式

      NSString *yourString = @"2016:10:13 17:48:42+0400";
      
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
      [dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ssZZZ"];
      
      NSDate *yourDate = [dateFormatter dateFromString:yourString];
      

      【讨论】:

        猜你喜欢
        • 2011-04-24
        • 2021-09-11
        • 2016-09-01
        • 2013-01-16
        • 2012-12-17
        • 2014-05-22
        相关资源
        最近更新 更多