与NSDate的工作,并与2012年新目标C比较
问题描述:
“31日 - 12月2010 9:00 AM至1:00 PM”与NSDate的工作,并与2012年新目标C比较
就拿上面的NSString,我需要将其转换成例如2个NSDates 2010年12月31日上午9:00和2010年12月31日1:00 PM
然后将它与当前日期进行比较,以查看当前日期是否落在给定日期之内。
因此2010年12月31日上午10:00将落入。
我想知道什么是最佳做法/技巧与目标C优雅地做到这一点?
答
事实证明,NSDateFormatter有一个dateFromString方法,它正是你想要的。
http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html
为NSDateFormatter的官方文档:
答
我最后做它像这样:
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");
为了比较我喜欢转换为unixtime(这被内置到obj-c)但这只是我的偏好! – 2011-01-05 23:57:19
在阅读使用NSDate的compare:方法的代码时,我总是不得不考虑比我想要的更长的时间,所以我在NSDate上编写了一个实现lessThan :, lessThanOrEqual:的类,它使用compare:underneath。编码时我发现读起来更容易。 – nall 2011-01-06 01:39:23
请分享代码! :P – 2011-01-06 02:35:21