アプリの起動時に、日付が 9:00 から 18:00 の間であるかどうかを確認したいと考えています。
そして、 を使って今の時間を取得できますNSDate
。時間を確認するにはどうすればよいですか?
アプリの起動時に、日付が 9:00 から 18:00 の間であるかどうかを確認したいと考えています。
そして、 を使って今の時間を取得できますNSDate
。時間を確認するにはどうすればよいですか?
非常に多くの答えと非常に多くの欠陥...
NSDateFormatter
日付から使いやすい文字列を取得するために使用できます。しかし、その文字列を日付の比較に使用するのは非常に悪い考えです!
文字列の使用に関する質問への回答は無視してください...
日付の年、月、日、時、分などに関する情報を取得する場合は、 and を使用する必要がNSCalendar
ありNSDateComponents
ます。
日付が 9:00 から 18:00 の間であるかどうかを確認するには、次のようにします。
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];
if (dateComponents.hour >= 9 && dateComponents.hour < 18) {
NSLog(@"Date is between 9:00 and 18:00.");
}
編集:
おっと、使用dateComponents.hour <= 18
すると、18:01 などの日付に対して間違った結果が得られます。dateComponents.hour < 18
行く方法です。;)
今日の09:00と18:00の日付を作成し、現在の時刻をそれらの日付と比較します。
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [cal components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:9];
[components setMinute:0];
[components setSecond:0];
NSDate *nineHundred = [cal dateFromComponents:components];
[components setHour:18];
NSDate *eighteenHundred = [cal dateFromComponents:components];
if ([nineHundred compare:now] != NSOrderedDescending &&
[eighteenHundred compare:now] != NSOrderedAscending)
{
NSLog(@"Date is between 09:00 and 18:00");
}