iOS获取某个时间段

- (NSDate *)getCustomDateWithHour:(NSInteger)hour
{

获取当前时间

NSDate *currentDate = [NSDate date];
NSCalendar*currentCalendar=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *currentComps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
NSLog(@"-----------weekday is %zd",[currentComps weekday]);//在这里需要注意的是:星期日是数字1,星期一时数字2,以此类推。。。

设置当天的某个点

NSDateComponents*resultComps=[[NSDateComponentsalloc]init];
[resultComps setYear:[currentComps year]];
[resultComps setMonth:[currentComps month]];
[resultComps setDay:[currentComps day]];
[resultComps setHour:hour];
NSCalendar*resultCalendar=[[NSCalendaralloc]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)
{
NSLog(@"该时间在 %ld:00-%ld:00 之间!", (long)fromHour, (long)toHour);
return YES;
}
return NO;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容