LoginSignup
5
7

More than 5 years have passed since last update.

Swiftで指定月の日数を得る

Last updated at Posted at 2018-04-03

実行環境、Xcode 9.2 + Swift 4.0

for month in 1...12 {
    let calendar = Calendar(identifier: .gregorian)
    var components = DateComponents()
    components.year = 2012
    // 日数を求めたい次の月。13になってもOK。ドキュメントにも、月もしくは月数とある
    components.month = month + 1
    // 日数を0にすることで、前の月の最後の日になる
    components.day = 0
    // 求めたい月の最後の日のDateオブジェクトを得る
    let date = calendar.date(from: components)!
    let dayCount = calendar.component(.day, from: date)
    print("\(month)\(dayCount)日")
}

結果。※2012年はうるう年。

1月 31日
2月 29日
3月 31日
4月 30日
5月 31日
6月 30日
7月 31日
8月 31日
9月 30日
10月 31日
11月 30日
12月 31日
5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7