简体   繁体   中英

Get date from description string in Objective-C

I would like to know if there is a way to find and convert a date from a string which contain some other informations like :

"Your driver will be here on Monday" or "Be present the November 24th" for example.

In order to create a NSDate from this information.

Thank you guys !

Please try below function:

-(void)fetchDateFromString:(NSString*)stringObj
{

    NSError *error = NULL;
    NSDataDetector *detectorObj = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeDate error:&error];

    NSArray *matchesObj = [detectorObj matchesInString:stringObj
                                         options:0
                                           range:NSMakeRange(0, [stringObj length])];

    NSLocale* currentLoc = [NSLocale currentLocale];
    for (NSTextCheckingResult *match in matchesObj) {
        if ([match resultType] == NSTextCheckingTypeDate) {
            NSLog(@"Date : %@", [[match date] descriptionWithLocale:currentLoc]);
        }
    }
}

And invoke as below:

[self fetchDateFromString:@"Be present the November 24th"];

Good Luck.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM