1

ログインした名前でモーニング/アフタヌーン/イブニングを表示するIOSアプリケーション。例: おはよう Mr.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 に答える