我想检查当前时间是否在两个时间之间。
例如,我想检查当前时间是在今天早上 10AM 到 12PM 之间还是明天早上 10AM 到 12PM 之间。我怎样才能做到这一点?
尝试这个
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
此解决方案适用于 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
}
这就是为我做的:
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
}
在斯威夫特:
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")
}