当我的应用程序启动时,我想检查日期是否在9:00-18:00之间.
@H_502_2@而现在我可以使用NSDate了.如何检查时间?
解决方法
这么多的答案和这么多的缺陷…
@H_502_2@您可以使用NSDateFormatter从日期获取用户友好的字符串.但是使用该字符串进行日期比较是一个非常糟糕的主意!
请忽略涉及使用字符串的任何问题的答案 @H_502_2@如果您想要获取有关日期年,月,日,时,分等信息,您应该使用NSCalendar和NSDateComponents. @H_502_2@为了检查日期是否在9:00至18:00之间,您可以执行以下操作:
请忽略涉及使用字符串的任何问题的答案 @H_502_2@如果您想要获取有关日期年,月,日,时,分等信息,您应该使用NSCalendar和NSDateComponents. @H_502_2@为了检查日期是否在9:00至18:00之间,您可以执行以下操作:
@H_502_2@编辑:使用dateComponents.hour< = 18的Whoops将导致18:01之间的日期错误的结果. dateComponents.hour< 18是去的路. ;)
- 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.");
- }