本文介绍了申请展示上午,傍晚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
IOS应用程序显示已登录名称"的上午/下午/傍晚".例如:早安X先生就是这样.
IOS application to display Morning/Afternoon/Evening with logged in Name. eg: Good Morning Mr.X like this.
需要从当前日期和时区计算这些事件
Need to calculate those event from current date and time zone
推荐答案
// For calculating the current date
NSDate *date = [NSDate date];
// Make Date Formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh a"];
// hh for hour mm for minutes and a will show you AM or PM
NSString *str = [dateFormatter stringFromDate:date];
NSLog(@"%@", str);
// Sperate str by space i.e. you will get time and AM/PM at index 0 and 1 respectively
NSArray *array = [str componentsSeparatedByString:@" "];
// Now you can check it by 12. If < 12 means Its morning > 12 means its evening or night
NSString *message;
NSString *personName = @"Mr.X";
NSString *timeInHour = array[0];
NSString *am_pm = array[1];
if([timeInHour integerValue] < 12 && [am_pm isEqualToString:@"AM"])
{
message = [NSString stringWithFormat:@"Good Morning %@", personName];
}
else if ([timeInHour integerValue] <= 4 && [am_pm isEqualToString:@"PM"])
{
message = [NSString stringWithFormat:@"Good Afternoon %@", personName];
}
else if ([timeInHour integerValue] == 12 && [am_pm isEqualToString:@"PM"])
{
message = [NSString stringWithFormat:@"Good Afternoon %@", personName];
}
else if ([timeInHour integerValue] > 4 && [am_pm isEqualToString:@"PM"])
{
message = [NSString stringWithFormat:@"Good Night %@", personName];
}
NSLog(@"%@", message);
使用NSCalendar您还可以获取小时:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:NSHourCalendarUnit fromDate:date];
NSInteger hour = [dateComponents hour];
if (hour < 12)
{
// Morning
}
else if (hour > 12 && hour <= 16)
{
// Afternoon
}
else
{
// Night
}
这篇关于申请展示上午,傍晚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!