如何从String获取日期,时间和金额

时间:2014-09-10 09:08:01

标签: ios arrays xcode nsstring

我有

NSstring *str = @"Existing applications can be improved or extended on 11-01-2014 at 4 PM for 120$ ";

从上面的字符串我想得到日期,时间和金额。上面的字符串我试图动态地获取..

我试过的是

NSArray *arySeperator = [result componentsSeparatedByString:@" "];
for(int i=0;i< [arySeperator count];i++)
{

}

无法继续......

请提供有关如何进一步处理的任何帮助或建议?

2 个答案:

答案 0 :(得分:6)

试试这个

 NSString *str = @"Existing applications can be improved or extended on 11-01-2014";
    NSString *aStrDate = [str substringFromIndex:[str rangeOfString:@" " options:NSBackwardsSearch].location + 1];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // this is imporant - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *dateFromString = [[NSDate alloc] init];
    // voila!
    dateFromString = [dateFormatter dateFromString:aStrDate];

答案 1 :(得分:4)

我认为这种方法更适合查找日期:它使用NSDataDetector来检测半结构化信息,例如日期,地址,链接,电话号码和公交信息。

 NSString *str = @"Existing applications can be improved or extended on 11-01-2014";

    NSError *error;
    NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];

    NSDate *date = [dataDetector firstMatchInString:str
                                            options:NSMatchingReportCompletion
                                              range:NSMakeRange(0, str.length)].date;



    NSLog(@"date: %@", date);