Xcode 、Android開発で今日の曜日算出

Xcode 、Android開発で今日の曜日算出

指定した日付の曜日を算出します。
祝祭日は、年月日固有での判定が必要です。
算出結果 1:日曜、2月曜、3:火曜、4:水曜、5:木曜、6:金曜、7:土曜

Objective-c
1// 現在日付を取得
2NSDate *now = [NSDate date];
3 
4NSCalendar *calendar = [NSCalendar currentCalendar];
5NSDateComponents *comps;
6 
7// 曜日
8comps = [calendar components:NSWeekdayCalendarUnit fromDate:now];
9NSInteger weekday = comps.weekday; // 曜日(1が日曜日 7が土曜日)
Swift
1// 現在日付を取得
2    let date: NSDate = NSDate()
3    let cal: NSCalendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
4// 曜日
5    let comp: NSDateComponents = cal.components([NSCalendarUnit.Weekday], fromDate: date)
6    let weekday: Int = comp.weekday
 
Android
1//現在日時より曜日算出する場合
2 
3    int weekday = calendar.get(Calendar.DAY_OF_WEEK)
4 
5//指定日より曜日算出する場合
6 
7    int Wyear  = 2016//指定日の年
8    int Wmonth  = 4;    //指定日の月
9    int Wday  = 1;      //指定日の日
10 
11    int weekday = calendar.set(Wyear,Wmonth - 1,Wday);

指定月のセットは、1減算してセットする。

Verified by MonsterInsights