How to check whether now date is during 9:00-18:00

感情迁移 提交于 2019-12-31 21:21:05

问题


When my app is launched I want to check whether the date is between 9:00-18:00.

And I can get the time of now using NSDate. How can I check the time?


回答1:


So many answers and so many flaws...

You can use NSDateFormatter in order to get an user-friendly string from a date. But it is a very bad idea to use that string for date comparisons!
Please ignore any answer to your question that involves using strings...

If you want to get information about a date's year, month, day, hour, minute, etc., you should use NSCalendar and NSDateComponents.

In order to check whether a date is between 9:00 and 18:00 you can do the following:

NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];

if (dateComponents.hour >= 9 && dateComponents.hour < 18) {
    NSLog(@"Date is between 9:00 and 18:00.");
}

EDIT:
Whoops, using dateComponents.hour <= 18 will result in wrong results for dates like 18:01. dateComponents.hour < 18 is the way to go. ;)




回答2:


Construct dates for 09:00 and 18:00 today and compare the current time with those dates:

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [cal components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];

[components setHour:9];
[components setMinute:0];
[components setSecond:0];
NSDate *nineHundred = [cal dateFromComponents:components];

[components setHour:18];
NSDate *eighteenHundred = [cal dateFromComponents:components];

if ([nineHundred compare:now] != NSOrderedDescending &&
    [eighteenHundred compare:now] != NSOrderedAscending)
{
    NSLog(@"Date is between 09:00 and 18:00");
}


来源:https://stackoverflow.com/questions/15019583/how-to-check-whether-now-date-is-during-900-1800

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!