1

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

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

4

2 回答 2

8
// 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
}
于 2013-07-23T04:32:06.757 回答
1

你可以使用NSDateComponents

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
if (currentHour >= 0 && currentHour < 12) {
    //@"Good Morning
} else if (currentHour >= 12 && currentHour < 17) {
    //Good Afternoon
} else if (currentHour >= 17 && currentHour < 21) {
    //Good Evening
} else {
    //"Good Night
}
于 2017-07-11T10:13:01.653 回答