6

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

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

4

4 回答 4

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

我从如何比较时间中得到这个

于 2012-12-20T05:36:55.913 回答
6

此解决方案适用于 swift 4

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


func CheckTimeExist()->Bool{

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
}
于 2019-03-13T10:04:13.320 回答
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

}
于 2017-02-17T11:13:58.760 回答
1

在斯威夫特:

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")
}
于 2018-06-27T00:03:10.077 回答