快速日期:如何判断一个月是否可以有have日? [英] Swift Date: How to tell if a month can have a leap day?

查看:73
本文介绍了快速日期:如何判断一个月是否可以有have日?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个日历视图,我想不知道这一年,只列出一个月内可能出现的所有日期。即以显示日历中的最大天数,例如2月29日。 从这里答案,我知道还有其他日历系统也有leap日,因此我很好奇如何能够确定日历是否具有a日,而与日历系统或年份无关。任何帮助将不胜感激!这是我目前要获取的一个月中的天数:

I'm building a calendar view that I want to be agnostic of the year, just list all the possible dates that can occur in a month. I.e. to show the maximum number of days in a calendar, like February 29th. From this answer, I know there are other calendar systems that also have leap days, so I'm curious how I might be able to tell if a calendar has a leap day, regardless of the calendar system or year. Any help would be greatly appreciated! Here is what I have currently to get the number of days in a month:

func days(in month: Int) -> Int {
    let components = DateComponents(month: month+1, day: -1)
    let lastDay = Calendar.current.date(from: components)!
    return Calendar.current.dateComponents([.day], from: lastDay).day!+1
}

这很好用,但是基于当前年份,可能不是a年。

This works great, but is based on the current year, which may not be a leap year.

我见过 isLeapMonth ,但这似乎与 .day

推荐答案

编辑/更新

您将获得下一个飞跃当前日历的年份,并检查每月的最大天数,例如:

You can get the next leap year for the current calendar and check the maximum number of days in month, maybe something like this:

extension Date {

    var year: Int { Calendar.current.component(.year, from: self) }

    var isLeapYear: Bool { Calendar.current.range(of: .day, in: .year, for: self)!.count == 366 }

    // find the leap year
    static var leapYear: Int {
        var year = Date().year
        while DateComponents(calendar: .current, year: year).date?.isLeapYear == false {
            year += 1
        }
        return year
    }
}







Date.leapYear  // 2020







func maximumNumberOfDays(in month: Int) -> Int? {
    Calendar.current.range(of: .day,
                           in: .month,
                           for: DateComponents(calendar: .current,
                                               year: Date.leapYear,
                                               month: month).date!)?.count
}







maximumNumberOfDays(in: 2)  // 29

这篇关于快速日期:如何判断一个月是否可以有have日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆