時間処理は、開発において、しばしば遭遇します。一般的には、特定の年、月、曜日、2つの異なる時刻の差、その日の前後の日などにアクセスできますが、ここでは特定の年、月、曜日、その日の前後の日だけを紹介する方法です。
時間を扱うには、一般的にNSDateクラスとNSCalendarクラスの2つのクラスを使います。
現在時刻の取得は次のとおりです。NSDate *nowDate = [NSDate date]; 特定の年と月と日を取得するnowDateの処理です。一般的にNSCalendarクラスを使用するには、まず、NSCalendarの宣言、および属性のセットアップです。intのnowYear = [comps year]のように、プロパティを設定すると、年、月、日を取得するメソッドに基づいてすることができます;
曜日を取得するには、まずint nowWeek = [comps weekday]を取得します。次に、nowweekの値を判断します。nowweekの値は1から7まであり、それぞれ日曜日から土曜日までの週に対応しています。
コードは以下の通り:
NSDate *nowDate = [NSDate date]; //これは現在時刻であり、実際にはどの時刻でもよい。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps;
comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:nowDate];
int nowYear = [comps year];
int nowMonth = [comps month];
int nowDay = [comps day];
int nowWeek = [comps weekday];
NSString *weekStr = [[NSString alloc] init];
switch (nowWeek) {
case 1:
weekStr = @" 曜日";
break;
case 2:
weekStr = @" 曜日";
break;
case 3:
weekStr = @"火曜日";
break;
case 4:
weekStr = @"水曜日";
break;
case 5:
weekStr = @"木曜日";
break;
case 6:
weekStr = @"金曜日";
break;
case 7:
weekStr = @"土曜日";
break;
default:
break;
}
NSLog(@" :%d;月:%d;日:%d;%@",nowYear,nowMonth,nowDay,weekStr);
特定の日の前日または翌日の方法:
ここで使用するのはNSCalendarで、最初にプロパティを設定するのも上記と同じです。最も重要なメソッドは[cps setHour:+24]で、+24は翌日、-24は前日を取得することを意味します;
*** カレンダーをNSdateに変換します:
NSDate *nowDate = [calendar dateByAddingComponents:comps toDate:showDate options:0]; //showDatenowDateはshowDateの前日または翌日の日付を表す。
コードは以下の通り:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps;
comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]];
[comps setHour:+24]; //+24は翌日の日付を取得、-24は前日の日付を取得する;
[comps setMinute:0];
[comps setSecond:0];
NSDate *nowDate = [calendar dateByAddingComponents:comps toDate:showDate options:0]; //showDatenowDateはshowDateの前日または翌日の日付を表す。