現在の時刻が2時間の間にあるかどうかを確認したい。
たとえば、現在の時刻が今日の午前10時から午後12時の間か、明日の朝の午前10時から午後12時までかを確認したいと思います。これどうやってするの?
これを試して
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をあなたの時間に置き換えます
時間を比較する方法からこれを取得します
このソリューションはswift4用です
システムから現在の時刻を取得し、その範囲に存在するかどうかを確認します。この場合、時間範囲は午前10時から午後6時です。
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
}
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")
}