20

日付が本質的に明日かどうかを確認するにはどうすればよいですか?

今日のような日付に時間や何かを追加したくありません。なぜなら、今日がすでにである場合22:59、追加しすぎると翌日になり、時間が である場合に追加しすぎると、12:00明日は逃してしまうからです。

NSDate2 つの s をチェックして、一方が他方の明日に相当することを確認するにはどうすればよいですか?

4

3 に答える 3

52

を使用NSDateComponentsすると、今日を表す日付から日/月/年のコンポーネントを抽出し、時間/分/秒のコンポーネントを無視して、1 日を追加し、明日に対応する日付を再構築できます。

したがって、現在の日付に正確に 1 日を追加したいとします (時間/分/秒の情報を「現在」の日付と同じに保つことを含む) dateWithTimeIntervalSinceNow。ただし、次を使用してこの方法で行う方が良いです(およびDSTプルーフなど)NSDateComponents

NSDateComponents* deltaComps = [[[NSDateComponents alloc] init] autorelease];
[deltaComps setDay:1];
NSDate* tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];

しかし、明日の午前 0 時に対応する日付を生成したい場合は、代わりに、時間/分/秒の部分なしで、現在を表す日付の月/日/年のコンポーネントを取得し、1 日を追加して、日付を再構築することができます。

// Decompose the date corresponding to "now" into Year+Month+Day components
NSUInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:[NSDate date]];
// Add one day
comps.day = comps.day + 1; // no worries: even if it is the end of the month it will wrap to the next month, see doc
// Recompose a new date, without any time information (so this will be at midnight)
NSDate *tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];

PS: Date and Time Programming Guide、特にhere about date componentsで、日付の概念に関する非常に役立つアドバイスや情報を読むことができます。

于 2012-10-01T22:31:16.780 に答える