月圆之夜,紫禁之巅,一剑西来,天外飞仙。

0%

iOS 判断当前时间在某个时间段内

在项目开发中可能会遇到这样的问题,判断当前的时间是否在指定的时间段内。下面直接上代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
- (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour
{

NSDate *dateFrom = [self getCustomDateWithHour:fromHour];

NSDate *dateTo = [self getCustomDateWithHour:toHour];

NSDate *currentDate = [NSDate date];

if ([currentDate compare:dateFrom]==NSOrderedDescending && [currentDate compare:dateTo]==NSOrderedAscending)
{

SLog(@"该时间在 %ld:00-%ld:00 之间!", (long)fromHour, (long)toHour);

return YES;

}
else
{
SLog(@"不在该时间段 %ld:00-%ld:00 之间!", (long)fromHour, (long)toHour);

return NO;
}

}


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

//获取当前时间

NSDate *currentDate = [NSDate date];

NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *currentComps = [[NSDateComponents alloc] init];



NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;



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:NSCalendarIdentifierGregorian];

return [resultCalendar dateFromComponents:resultComps];

}

点击并拖拽以移动

用法:

1
2
//在 9 - 20 点之间
[self isBetweenFromHour:9 toHour:20];

点击并拖拽以移动