在我的应用程序中,我有一个字符串 - “比赛将从dd / mm / yyyy开始到dd / mm / yyyy”我希望两个日期分开,所以我需要一种方法将这些日期存储在两个不同的字符串中。 / p>
答案 0 :(得分:1)
你可以用正则表达式(半公然改编自here)来做到这一点。
NSString *string = @"contest will start from 10/11/2012 to 12/11/2012";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"from (.*) to (.*)"
options:0
error:NULL];
NSTextCheckingResult *results = [regex firstMatchInString:string
options:0
range:NSMakeRange(0, [string length])];
NSString *date1 = [string substringWithRange:[results rangeAtIndex:1]];
NSString *date2 = [string substringWithRange:[results rangeAtIndex:2]];
答案 1 :(得分:0)
NSString *dateString = @"contest will start from dd/mm/yyyy to dd/mm/yyyy";
NSArray *components = [dateString componentsSeparatedByString:@"to"];
NSString *firstDate = [[components objectAtIndex:0] stringByReplacingOccurrencesOfString:@"contest will start from "];
NSString *secondDate = [[components objectAtIndex:1] stringByReplacingOccurrencesOfString:@" "];
答案 2 :(得分:0)
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:units fromDate: date];
NSInteger year = [components year];
NSInteger month = [components month];
NSInteger day = [components day];
NSString *together = [NSString stringWithFormat:@"%i - %i - %i", day, month, year];