iphone - 申请显示早上,晚上

标签 iphone ios

IOS 应用程序以登录名称显示早上/下午/晚上。 例如:像这样的早安 X 先生。

需要从当前日期和时区计算那些事件

最佳答案

// 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
}

关于iphone - 申请显示早上,晚上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17801505/

相关文章:

ios - 转至 Storyboard Reference 后出错

iphone - iOS 4.0 缺少框架

iphone - 从代码打开 map 应用程序 - 在哪里/如何找到 "Current Location"?

ios - 短暂超时后如何切换到新的 View Controller ?

iphone - 如何使用 SA_OAuthTwitterEngine 在没有 PIN 的情况下从 iPhone 发布推文?

iphone - AVPlayer 设置初始播放时间 iOS

ios - 如何将 NSDictionary 数据绑定(bind)到 objective-c 中的 TableView ?

ios - Xcode, swift : How to detect link click and stop redirecting Safari?

iphone - 如何使用 NSOutputStream 通过套接字发送 NSString

ios - 在我的应用程序中添加设置页面(Xcode 和 Swift)