1-(BOOL) Isbetweenfromhour: (Nsinteger) Fromhour tohour: (nsinteger) Tohour2 {3NSDate *date8 = [Self getcustomdatewithhour:8];4NSDate *date23 = [Self getcustomdatewithhour: at];5NSDate *currentdate =[NSDate Date];6 7 if([currentdate compare:date8]==nsordereddescending && [currentdate compare:date23]==nsorderedascending)8 {9NSLog (@"the time is between%ld:00-%ld:00! ", (Long) Fromhour, (Long) tohour);Ten returnYES; One } A returnNO; - } - /** the * @brief generate a point on the day (London time is returned, which can be compared directly to the current time [NSDate Date]) - * @param hour such as hour for "8", that is, 8:00 (local time) - */ --(NSDate *) Getcustomdatewithhour: (Nsinteger) Hour + { - //Get current Time +NSDate *currentdate =[NSDate Date]; A atNscalendar *currentcalendar =[[Nscalendar alloc] Initwithcalendaridentifier:nsgregoriancalendar]; -Nsdatecomponents *currentcomps =[[Nsdatecomponents alloc] init]; -Nsinteger unitflags = Nsyearcalendarunit | Nsmonthcalendarunit | Nsdaycalendarunit | Nsweekdaycalendarunit | Nshourcalendarunit | Nsminutecalendarunit |Nssecondcalendarunit; - //generate the component of the day -Currentcomps =[Currentcalendar components:unitflags fromdate:currentdate]; - //set a point for the day inNsdatecomponents *resultcomps =[[Nsdatecomponents alloc] init]; - [Resultcomps setyear:[currentcomps Year]]; to [resultcomps setmonth:[currentcomps Month]]; + [Resultcomps Setday:[currentcomps Day]; - [Resultcomps Sethour:hour]; the * //generate dates based on Resultcalendar and Resultcomps $Nscalendar *resultcalendar =[[Nscalendar alloc] Initwithcalendaridentifier:nsgregoriancalendar];Panax Notoginseng return[Resultcalendar datefromcomponents:resultcomps]; -}
IOS, using Nsdatecomponents,nscalendar to determine whether the current point in time is within a certain time period of the method