“2010年12月31日上午9:00至下午1:00”
以上面的NSString为例,我需要将其转换为2个NSDates,例如 2010年12月31日上午9:00和2010年12月31日下午1:00
然后将其与当前日期进行比较,以查看当前日期是否在给定日期内。
因此,2010年12月31日上午10:00将会落入其中。
我想知道Objective C有哪些最佳实践/技巧可以优雅地完成这项工作?
答案 0 :(得分:2)
事实证明,NSDateFormatter有一个dateFromString方法,它完全符合您的要求。
http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html
NSDateFormatter的官方文档:
答案 1 :(得分:0)
我最终这样做了:
NSString *temp = [[dateString allValues] objectAtIndex:0];
NSLog(@"temp: %@", temp);
NSArray *tokens = [temp componentsSeparatedByString: @" "];
NSArray *tokenOneDelimited = [[tokens objectAtIndex:0] componentsSeparatedByString: @"-"];
NSString *dateStr1 = [NSString stringWithFormat: @"%@-%@-%@ %@", [tokenOneDelimited objectAtIndex:2],
[tokenOneDelimited objectAtIndex:1],
[tokenOneDelimited objectAtIndex:0],
[tokens objectAtIndex:1]];
NSString *dateStr2 = [NSString stringWithFormat: @"%@-%@-%@ %@", [tokenOneDelimited objectAtIndex:2],
[tokenOneDelimited objectAtIndex:1],
[tokenOneDelimited objectAtIndex:0],
[tokens objectAtIndex:3]];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MMM-dd hh:mma"];
NSDate *myDate1 = [dateFormatter dateFromString: dateStr1];
NSDate *myDate2 = [dateFormatter dateFromString: dateStr2];
NSDate *currentDate = [NSDate date];
NSComparisonResult comparison = [currentDate compare: myDate1];
NSComparisonResult comparison2 = [currentDate compare: myDate2];
if (
comparison == NSOrderedDescending &&
comparison2 == NSOrderedAscending
)
{
NSLog(@"is On now");