日付関連は色々あるのでほんの一例です、自分が使いやすかった記述のメモになります。
Date関数(今日の日付)から年月日等を取得
currentを使用する、currentは端末から読み込むようで暦の設定は出来ない(.gregorianとか)
1 2 3 4 5 6 7 |
let a = Calendar.current.component(.year, from: Date()) let b = Calendar.current.component(.month, from: Date()) let c = Calendar.current.component(.day, from: Date()) let d = Calendar.current.component(.hour, from: Date()) let e = Calendar.current.component(.minute, from: Date()) let f = Calendar.current.component(.second, from: Date()) let g = Calendar.current.component(.weekday, from: Date()) //曜日をintで取得 1=日曜日 7 =土曜日 |
自分で日付を指定してComponent作成からDateへ
暦を設定してComponent(カレンダーの部品的な)を作る
日付操作をするためにはdate型にしてその変数を指定する、主に.dateで作る
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let a = Calendar(identifier: .gregorian) //グレゴリオ暦 let b = Calendar(identifier: .japanese) //和暦 let c = a.date(from: DateComponents(year: 2025, month: 3, day: 31) //2025年03月31日の【date型】が c に入る //↑を分けて書く(ex1~2) let ex1 = DateComponents(year: 2025, month: 5, day: 4) let ex2 = Calendar.current.date(from: ex1)! let d = a.component(.day, from: c ?? nil ?? Date()) //.day指定なので日にちを取得できる c で作った31日がint型で入る let e = a.range(of: .day, in: month, for: c)!.count //c の日にちの数、(最大日にち数) let f = a.component(.weekOfMonth, from: c) //c の週番号を取得できる 6 がintで入る、月初なら1 let g = a.component(.weekOfYear, from: c) //年初から数えて第何週目なのかを取得できる 14 |
日付操作例
byAddingで操作
1 2 3 4 5 6 7 |
//加算 let a = Calendar.current.date(byAdding: .year, value: 1, to: Date()) //今の日付から一年足す let b = Calendar.current.date(byAdding: .day, value: 2, to: Date()) //二日足す let b = Calendar.current.date(byAdding: .hour, value: 3, to: Date()) //三時間足す //減算 valueでマイナスするだけ let e = Calendar.current.date(byAdding: .minute, value: -4, to: Date()) //四分引く |
コメント