【问题标题】:Extract a date from a complex NSString从复杂的 NSString 中提取日期
【发布时间】:2015-03-07 19:27:16
【问题描述】:

我在 Xcode 中没有能力解决这个问题:

我有这段文字:

“402 加西亚 2015 年 1 月 8 日 10:26 Observaciones del huésped"

我想提取我确定是 GMT +0 的日期,然后添加电话 GMT,例如 GMT +1,并将旧日期替换为 NSString 中的新日期。

我刚刚在另一个地方解决了 GMT 问题,所以我只需要提取日期字符串并将其替换为字符串,这样我的最终结果将类似于:

“402 加西亚 2015 年 1 月 8 日 11:26 Observaciones del huésped"

任何帮助将不胜感激,并提前致谢。

【问题讨论】:

    标签: ios objective-c string date nsstring


    【解决方案1】:

    这正是NSDataDetector 的用途。

    我在 NSString 上的一个类别中创建了一个方法:

    @interface NSString (HASAdditions)
    
    - (NSArray *)detectedDates;
    
    @end
    
    
    @implementation NSString (HASAdditions)
    
    - (NSArray *)detectedDates {
        NSError *error = nil;
        NSDataDetector *dateDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];
        if (!dateDetector) return nil;
        NSArray *matches = [dateDetector matchesInString:self options:kNilOptions range:NSMakeRange(0, self.length)];
        NSMutableArray *dates = [[NSMutableArray alloc] init];
        for (NSTextCheckingResult *match in matches) {
            if (match.resultType == NSTextCheckingTypeDate) {
                [dates addObject:match.date];
            }
        }
        return dates.count ? [dates copy] : nil;
    }
    

    你可以这样称呼它:

    NSArray *dates = [@"402 Garcia 01/08/15 10:26 Observaciones del huésped" detectedDates];
    

    您可以在NSHipster 上阅读有关 NSDataDetector 的更多信息

    【讨论】:

      【解决方案2】:

      这项工作始终是相同的文本结构。

      NSString *text = @"402 Garcia 01/08/15 10:26 Observaciones del huésped";
      
      // This the formatter will be use.
      NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
      [formatter setDateFormat:@"dd/MM/yy HH:mm"];
      [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
      
      // First we extract the part of the text we need.
      NSArray *array = [text componentsSeparatedByString:@" "];
      NSString *dateString = [NSString stringWithFormat:@"%@ %@",[array objectAtIndex:2],[array objectAtIndex:3]];
      // Here the search text
      NSLog(@"%@",dateString);
      
      // Now we use the formatter and the extracted text.
      NSDate *date = [formatter dateFromString:dateString];
      
      NSLog(@"The date is: %@",[date description]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-17
        • 2021-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-27
        • 2023-03-24
        • 2020-09-30
        相关资源
        最近更新 更多