LoginSignup
1
0

More than 5 years have passed since last update.

Swiftで1年の日数を数える

Posted at

実行環境、Xcode 9.2 + Swift 4.0

let calendar = Calendar(identifier: .gregorian)
for year in 2010...2020 {
    var components = DateComponents()
    components.year = year
    components.month = 1
    components.day = 1
    let date1 = calendar.date(from: components)!

    components.year = year + 1
    components.month = 1
    components.day = 1
    let date2 = calendar.date(from: components)!

    components = calendar.dateComponents([.day], from: date1, to: date2)
    print("\(year)\(components.day!)日")
}

結果。うるう年は366日になっています。

2010年 365日
2011年 365日
2012年 366日
2013年 365日
2014年 365日
2015年 365日
2016年 366日
2017年 365日
2018年 365日
2019年 365日
2020年 366日
1
0
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
1
0