问题
How to compare time in Objective C?
if (nowTime > 9:00 PM) && (nowTime < 7:00 AM)
{
doSomething;
}
回答1:
If you want to get the current hour and compare it to some times, you're going to have to use NSDate
, NSDateComponents
, and NSCalendar
.
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
}
That will check if the time is between 9:00 PM and 7:00 AM. Of course, if you're going to want different times you'll have to change the code a little.
Read about NSDate, NSDateComponents, and NSCalendar to learn more.
回答2:
Theres a perfect formula for this. Just for future references
Below is the sample code :
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
NSString *startTime = @"21:00";
NSString *endTime = @"07:00";
int stHr = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
int stMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
int enHr = [[[endTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
int enMin = [[[endTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
int formStTime = (stHr*60)+stMin;
int formEnTime = (enHr*60)+enMin;
int nowTime = (int)((currHr*60)+currtMin);
if(nowTime >= formStTime && nowTime <= formEnTime) {
// Do Some Nasty Stuff..
}
回答3:
NSDate *now = [NSDate date];
if (([now compare:earlierDateVariable] == NSOrderedDescending) && ([now compare:laterDateVariable] == NSOrderedAscending ))
{
// Do something here...
}
To set earlierDate and laterDate, straight from Apple's documentation available here
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:22];
[comps setMonth:03];
[comps setYear:2011];
[comps setHour:21];
[comps setMinute:00];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *earlierDateVariable = [gregorian dateFromComponents:comps];
[comps release];
[gregorian release];
And the same goes for later date...
回答4:
For checking current time or any time between two times ::
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
return [self isDateComponent:components withinStartHour:startH startMin:startM endHour:endH endMin:endM];
-(BOOL)isDateComponent:(NSDateComponents*)components withinStartHour:(int)startH startMin:(int)startM endHour:(int)endH endMin:(int)endM
{
if (endH < startH) {
return ( [self isDateComponent:components betweenStartHour:startH startmin:startM endHour:23 endMin:59] ||
[self isDateComponent:components betweenStartHour:0 startmin:0 endHour:endH endMin:endM] );
}
else {
return [self isDateComponent:components betweenStartHour:startH startmin:startM endHour:endH endMin:endM];
}
}
-(BOOL)isDateComponent:(NSDateComponents*)components betweenStartHour:(int)startH startmin:(int)startM endHour:(int)endH endMin:(int)endM
{
int currentH = components.hour;
int currentM = components.minute ;
DDLogVerbose(@"start : %i-%i, end : %i-%i, current:%i-%i",startH,startM,endH,endM,currentH,currentM);
startM = startM + startH * 60;
endM = endM + endH * 60;
currentM = components.minute + currentH*60;
if ( startM <= currentM && currentM < endM ) {
return YES;
}
else {
return NO;
}
}
回答5:
I used the Answer Given above by rye. I just had to convert my 7:00 AM and 9:00 PM to 24 hours. Here's the method I used
/**
Willl return YES if the Restaurant is OPEN at the Moment else NO
*/
-(BOOL) isShopOpen:(NSString *) startTime closeTime:(NSString *) endTime{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
int stHr ;
int stMin ;
int enHr ;
int enMin ;
if([startTime containsString:@"PM"]){
startTime = [startTime stringByReplacingOccurrencesOfString:@" PM" withString:@""];
stHr=[[[startTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
stHr=stHr+12;
stMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
}else{
startTime = [startTime stringByReplacingOccurrencesOfString:@" AM" withString:@""];
stHr=[[[startTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
stMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
}
if([endTime containsString:@"PM"]){
endTime = [endTime stringByReplacingOccurrencesOfString:@" PM" withString:@""];
enHr=[[[endTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
enHr=enHr+12;
enMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
}else{
endTime = [endTime stringByReplacingOccurrencesOfString:@" AM" withString:@""];
enHr=[[[endTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
enMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
}
int formStTime = (stHr*60)+stMin;
int formEnTime = (enHr*60)+enMin;
int nowTime = (currHr*60)+currtMin;
if(nowTime >= formStTime && nowTime <= formEnTime) {
// Do Some Nasty Stuff..
return YES;
}else{
return NO;
}
}
回答6:
If anybody needs, this is a code to create sections in a tableView according to the date of objects.
Method to get dates for today, yesterday, etc. (taken from ReMail project DateUtil class):
#define DATE_UTIL_SECS_PER_DAY 86400
-(void)refreshData {
//TODO(gabor): Call this every hour or so to refresh what today, yesterday, etc. mean
NSCalendar *gregorian = [NSCalendar currentCalendar];
self.today = [NSDate date];
self.yesterday = [today dateByAddingTimeInterval:-DATE_UTIL_SECS_PER_DAY];
self.lastWeek = [today dateByAddingTimeInterval:-6*DATE_UTIL_SECS_PER_DAY];
self.todayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:today];
self.yesterdayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:yesterday];
self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
}
Method to sort tableData for table view sections according to date:
// Sort tableData objects according to the date
for (MCMessage *mcMessage in self.tableData) {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:mcMessage.dateTime];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSLog(@"Day:%d, Month:%d, Year:%d. Today day:%d. Yesterday:%d", day, month, year, dateUtil.todayComponents.day, dateUtil.yesterdayComponents.day);
if ((dateUtil.todayComponents.day == day) && (dateUtil.todayComponents.month == month) && (dateUtil.todayComponents.year == year))
{
[self.todayData addObject:mcMessage];
}
else if ((dateUtil.yesterdayComponents.day == day) && (dateUtil.yesterdayComponents.month == month) && (dateUtil.yesterdayComponents.year == year))
{
[self.yesterdayData addObject:mcMessage];
}
else
{
[self.soonerData addObject:mcMessage];
}
}
来源:https://stackoverflow.com/questions/5388551/how-to-compare-time