您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 判斷目前時間是否落在指定時段

編輯:iOS 開發綜合

在 iOS 中判斷目前時間是否落在某個時段,例如夜間勿擾模式,可以使用 NSCalendar 與 NSDateComponents 建立當天的指定時間點,再與目前時間比較。

建立指定時間

- (NSDate *)getCustomDateWithHour:(NSInteger)hour {
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSInteger year = [[calendar components:NSYearCalendarUnit fromDate:currentDate] year];
    NSInteger month = [[calendar components:NSMonthCalendarUnit fromDate:currentDate] month];
    NSInteger day = [[calendar components:NSDayCalendarUnit fromDate:currentDate] day];

    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    [resultComps setYear:year];
    [resultComps setMonth:month];
    [resultComps setDay:day];
    [resultComps setHour:hour];

    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    return [resultCalendar dateFromComponents:resultComps];
}

比較時段

- (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour {
    NSDate *fromDate = [self getCustomDateWithHour:fromHour];
    NSDate *toDate = [self getCustomDateWithHour:toHour];
    NSDate *currentDate = [NSDate date];

    if ([currentDate compare:fromDate] == NSOrderedDescending && [currentDate compare:toDate] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}

這種做法比字串拼接更清楚,也比較容易維護。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved