查找当前时间是否在一个范围之间

我可以find如何得到如果一个date之间的范围,但我似乎无法如何创build一个特定的date。

如果[NSDate date]在一个时间范围之内,最简单的方法是什么?

我想显示一个个性化的问候如下:

下午12点 – 4点59分:9999分@“下午好,富”
5 pm – 11:59:9999 pm @“晚上好,foo”
上午12点 – 11点59分:9999上午@“早上好,富”

是的,你可以使用NSDateComponents ,它将返回24小时格式的小时。

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:[NSDate date]]; NSInteger hour = [components hour]; if(hour >= 0 && hour < 12) NSLog(@"Good morning, foo"); else if(hour >= 12 && hour < 17) NSLog(@"Good afternoon, foo"); else if(hour >= 17) NSLog(@"Good evening, foo"); 

Swift 3

 let hour = Calendar.current.component(.hour, from: Date()) if hour >= 0 && hour < 12 { print("Good Morning") } else if hour >= 12 && hour < 17 { print("Good Afternoon") } else if hour >= 17 { print("Good Evening") } 

更新了Swift 3.0

 let hour = Calendar.current.component(.hour, from: Date()) if hour >= 0 && hour < 12 { print("Good Morning") } else if hour >= 12 && hour < 17 { print("Good Afternoon") } else if hour >= 17 { print("Good Evening") } 

使用NSCalendar实例从NSDate创build一个NSDateComponents实例,然后检查NSDateComponents的hours,minutes和seconds属性,并显示相应的消息。

中午下午12:00下午 12点01分到下午 5点左右晚上是从5点01分到 8点 ,或者在日落前后。 夜晚是从日落到日出,所以从8:01 PM到5:59 AM。

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:[NSDate date]]; [components setTimeZone:[NSTimeZone localTimeZone]]; NSInteger hour = [components hour]; if(hour >= 6 && hour < 12) NSLog(@"Good morning!"); else if(hour >= 12 && hour < 17) NSLog(@"Good afternoon!"); else if(hour >= 17 && hour < 20) NSLog(@"Good evening!"); else if((hour >= 20) || (hour >= 0 && hour < 6)) NSLog(@"Good night!"); 

您可以使用NSDate类来获取iPhone上的时间。

 NSDate * today = [NSDate date]; NSCalendar * cal = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar]; NSDateComponents * comps = [cal components:NSHourCalendarUnit fromDate:today]; if ( [comps hour]>0 && [comps hour] < 12 ) NSLog(@"Good morning, foo"); if ( [comps hour] > 12 && [comps hour] < 17 ) NSLog(@"Good afternoon, foo"); if ( [comps hour] >17 && [comps hour]<24 ) NSLog(@"Good evening, foo"); 

参考: NSDate文档