ios-检查当前时间是否在两次之间

时间:2012-12-20 05:32:37

标签: ios nsdate

我想检查当前时间是否在两次之间。

例如,我想检查当前时间是在今天早上10点到12点之间,还是明天早上10点到12点之间。我怎么能这样做?

4 个答案:

答案 0 :(得分:18)

试试这个

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];

if (currentHour < 7 || (currentHour > 21 || currentHour == 21 && (currentMinute > 0 || currentSecond > 0))) {
    // Do Something
}

用你的时间替换7,21

我是从How to compare time

得到的

答案 1 :(得分:2)

这就是为我做的事情:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinutes = [components minute];
NSInteger currentSeconds = [components second];
NSInteger day = [[NSDate date] dayOfTheWeek];

if (((currentHour > openHours) && (currentHour < closeHours)) ||
    ((currentHour == openHours) && (currentMinutes >= openMinutes)) ||
    ((currentHour == closeHours)&&(currentMinutes<=closeMinutes))) {

    //..do something

}

答案 2 :(得分:0)

在Swift中:

let componets = Calendar.current.dateComponents([.hour, .minute, .second], from: Date())
let currentHour = componets.hour
let currentMinute = componets.minute
let currentSecond = componets.second

if currentHour! < 7 || currentHour! > 21 {
    print ("do something")
} else {
    print ("do nothing")
}

答案 3 :(得分:0)

此解决方案适用于快速4

从系统获取当前时间,然后检查是否存在该范围。在这种情况下,时间范围是上午10:00到下午6:00


func CheckTimeExist()->布尔{

var timeExist:Bool
let calendar = Calendar.current
let startTimeComponent = DateComponents(calendar: calendar, hour:10)
let endTimeComponent   = DateComponents(calendar: calendar, hour: 18, minute: 00)

let now = Date()
let startOfToday = calendar.startOfDay(for: now)
let startTime    = calendar.date(byAdding: startTimeComponent, to: startOfToday)!
let endTime      = calendar.date(byAdding: endTimeComponent, to: startOfToday)!

if startTime <= now && now <= endTime {
    print("between 10 AM and 6:00 PM")
    timeExist = true
} else {
    print("not between 10 AM and 6:00 PM")
    timeExist = false
}
return timeExist

}