ios中利用NSDateComponents、NSDate、NSCalendar判斷目前時間是否在一天的某個時間段內。

來源:互聯網
上載者:User

標籤:nsdate   時間間隔   時間段   判斷時間是否在某個時間段內   

應用中設定一般會存在這樣的設定,如夜間勿擾模式,從8:00-23:00,此時如何判斷目前時間是否在該時間段內。痛點主要在於如何用NSDate產生一個8:00的時間和23:00的時間,然後用當前的時間跟這倆時間作對比就好了。

下面提供兩條思路:

法1.用NSDate產生目前時間,然後轉為字串,從字串中取出當前的年、月、日,然後再拼上時、分、秒,然後再將拼接後的字串轉為NSDate,最後用當前的時間跟自己產生的倆NSDate的時間點比較。(該方法比較笨,也不難,但看起來有點太菜了,看上去不怎麼規範)

法2.用NSDateComponents、NSCalendar確定倆固定的NSDate格式的時間,然後再進行比較(此方法比較裝逼,其實跟拼字串的方法複雜度差不了多少,但看起來比較規範,像是大神寫的)。

/** * @brief 判斷目前時間是否在fromHour和toHour之間。如,fromHour=8,toHour=23時,即為判斷目前時間是否在8:00-23:00之間 */- (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour{    NSDate *date8 = [self getCustomDateWithHour:8];    NSDate *date23 = [self getCustomDateWithHour:23];        NSDate *currentDate = [NSDate date];        if ([currentDate compare:date8]==NSOrderedDescending && [currentDate compare:date23]==NSOrderedAscending)    {        NSLog(@"該時間在 %d:00-%d:00 之間!", fromHour, toHour);        return YES;    }    return NO;}/** * @brief 產生當天的某個點(返回的是倫敦時間,可直接與目前時間[NSDate date]比較) * @param hour 如hour為“8”,就是上午8:00(本地時間) */- (NSDate *)getCustomDateWithHour:(NSInteger)hour{    //擷取目前時間    NSDate *currentDate = [NSDate date];    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    NSDateComponents *currentComps = [[NSDateComponents alloc] init];        NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;        currentComps = [currentCalendar components:unitFlags fromDate:currentDate];        //設定當天的某個點    NSDateComponents *resultComps = [[NSDateComponents alloc] init];    [resultComps setYear:[currentComps year]];    [resultComps setMonth:[currentComps month]];    [resultComps setDay:[currentComps day]];    [resultComps setHour:hour];        NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    return [resultCalendar dateFromComponents:resultComps];}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.