12

アプリの起動時に、日付が 9:00 から 18:00 の間であるかどうかを確認したいと考えています。

そして、 を使って今の時間を取得できますNSDate。時間を確認するにはどうすればよいですか?

4

2 に答える 2

19

非常に多くの答えと非常に多くの欠陥...

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行く方法です。;)

于 2013-02-22T09:37:36.833 に答える
6

今日の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");
}
于 2013-02-22T08:21:44.487 に答える