应用于显示早晨,晚上

时间:2013-07-23 04:27:49

标签: iphone ios

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

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

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

您可以使用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
}