我有一個關於NSDate的查詢。我有一個日期,即「2011-10-04 07:36:38 +0000」,我想檢查這個日期是否是昨天,或者今天或未來的日期。檢查指定日期是今天,昨天還是未來日期
我該怎麼辦?
我有一個關於NSDate的查詢。我有一個日期,即「2011-10-04 07:36:38 +0000」,我想檢查這個日期是否是昨天,或者今天或未來的日期。檢查指定日期是今天,昨天還是未來日期
我該怎麼辦?
試試這個:
注意:根據您的需要更改日期格式。
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/yyyy"];
NSDate* enteredDate = [df dateFromString:@"10/04/2011"];
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:enteredDate];
switch (result)
{
case NSOrderedAscending:
NSLog(@"Future Date");
break;
case NSOrderedDescending:
NSLog(@"Earlier Date");
break;
case NSOrderedSame:
NSLog(@"Today/Null Date Passed"); //Not sure why This is case when null/wrong date is passed
break;
}
使用任何如下因素根據烏拉圭回合的需要,
– earlierDate:
– laterDate:
– compare:
這不適用於iOS開發。 從網站上,很明顯這樣說: 「可用性\t可用於OS X v10.0及更高版本。」 – JHHoang
見Apple's documentation on date calculations:
NSDate *startDate = ...;
NSDate *endDate = ...;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
如果days
是+1和-1,那麼您的日期之間是「今天」的候選人。顯然你需要考慮你如何處理小時。推測最簡單的方法是將所有日期設置爲當天00:00時(truncate the date using an approach like this),然後使用這些值進行計算。這樣你今天得到0,昨天得到-1,明天得+1,而其他任何價值都會告訴你未來或過去有多遠。
這會起作用,但爲避免夏時制變化出現錯誤,將小時設置爲中午(12:00:00)會更安全。 – Suz
具有諷刺意味的是,我原來建議將時間設置爲中午,但截斷的例子已將其設置爲午夜,我認爲可以保持一致!但是,如果兩個日期都在同一個時區,那麼這將不會產生任何影響,因爲夏令時會在凌晨2點發生變化,並將時鐘恢復爲凌晨1點,因此在所有情況下,來自同一時區的兩個日期將截斷爲相同的日曆日期,無論夏時制如何。 –
如果您實際上想要考慮時區,最好的方法是在做其他任何事情之前將這兩個日期轉換爲同一時區。 –
-(NSString*)timeAgoFor:(NSString*)tipping_date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:tipping_date];
NSString *key = @"";
NSTimeInterval ti = [date timeIntervalSinceDate:[NSDate date]];
key = (ti > 0) ? @"Left" : @"Ago";
ti = ABS(ti);
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:date];
if (result == NSOrderedSame) {
return[NSString stringWithFormat:@"Today"];
}
else if (ti < 86400 * 2) {
return[NSString stringWithFormat:@"1 Day %@",key];
}else if (ti < 86400 * 7) {
int diff = round(ti/60/60/24);
return[NSString stringWithFormat:@"%d Days %@", diff,key];
}else {
int diff = round(ti/(86400 * 7));
return[NSString stringWithFormat:@"%d Wks %@", diff,key];
}
}
我用這個,但不知何故今天從來沒有過,所以我不得不修改它,以便我只比較日期。休息工作正常。最後得到了它與它的時間比較的問題。我必須做相應的調整 – ChArAnJiT
每個案例陳述後應該有一箇中斷,以免在其他案件中輸入。 –
請注意,這將永遠不會返回「今天」 - NSDate代表一個特定的時間即時,所以'NSOrderedSame'將(實質上)永遠不會發生 – Tim