「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優雅地做到這一點?
「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