查找当前时间是否在范围之间 [英] Find if current time is between a range
问题描述
如果日期介于某个范围之间,我可以找到如何获取,但我似乎无法在特定时间创建日期。
I can find how to get if a date is between a range, but I cant seem how to create a date at a specific time.
什么是查看[NSDate日期]是否在时间范围之间的最简单方法是?
What would be the simplest way to see if [NSDate date] is between a time range?
我想显示如下的个性化问候语:
I want to display a personalized greeting like the following:
12 pm - 4:59:9999 pm @下午好,foo
下午5点 - 晚上11:59:9999 @晚上好, foo
12 am - 11:59:9999 am @早上好,foo
12 pm - 4:59:9999 pm @"Good afternoon, foo"
5 pm - 11:59:9999 pm @"Good evening, foo"
12 am - 11:59:9999 am @"Good morning, foo"
推荐答案
是的,您可以使用 NSDateComponents
将以24小时格式返回小时。
Yes you can using NSDateComponents
which will return the hour in the 24 hour format.
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")
}
这篇关于查找当前时间是否在范围之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!