Working with NSDate and Comparing with Dates in Objective C
"31-Dec-2010 9:00AM to 1:00PM"
Take the above NSString for example, I need to convert it to 2 NSDates e.g. 31-Dec-2010 9:00AM AND 31-Dec-2010 1:00PM
Then compare it with the current Date to see if the current date falls within the given dates.
So 31-Dec-2010 10:00AM would fa开发者_高级运维ll within.
I'm wondering What are the best practices/tricks are with Objective C to do this elegantly?
As it turns out, NSDateFormatter has a dateFromString method, which does exactly what you want.
http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html
The official documentation for NSDateFormatter:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html
I ended up doing it like so:
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");
精彩评论