AI Engineering Service

AI Engineering Serviceの公式ブログです。開発者のプライベートな内容を含みます。

【swift5】ある月の日数を数える

f:id:ibarakito:20190723235723p:plain

ある月の日数をゲットしたいと思ったとします。
1,3,5,7,8,10,12月は31日、それ以外は30日で2月だけ28日か29日です。
switch文での定義ではある年では良いのですが閏年には対応できません。
コードでうまく表現する方法を模索した結果、以下のようなものに落ち着きました。

    private func daysOfMonth() -> Int{
        let datenow :Date = Date()
        let calendar = Calendar(identifier: .gregorian)
        var components = DateComponents()
        components.year = Calendar.current.component(.year, from: datenow)
        components.month = Calendar.current.component(.month, from: datenow) + 1
        components.day = 0
        let date = calendar.date(from: components)!
        let dayCount = calendar.component(.day, from: date)
        return dayCount
    }

これは調べたい月の翌月の0日(=調べたい月の最終日)の日付をコンポーネントで作り、
その最終日のdayの値をもってして月の日数だとしています。

プライバシーポリシー / お問い合わせ