2012-12-20 83 views
3

我想檢查當前時間是否在兩次之間。ios-檢查當前時間是否在兩次之間

例如,我想檢查當前時間是在今天上午10點到12點之間還是明天上午10點到12點之間。我怎樣才能做到這一點?

回答

17

試試這個

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

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 

} 
+1

此檢查井蓋一些情況不在上述接受消息的範圍內。例如8點半至18點之間開放的商店。當前時間是11:50。 –

+1

此檢查需要幾分鐘時間才能完成。 –

相關問題