swift4.0

UIDatePicker一个自定义日期选择器获取日期数据的问题

2019-05-08  本文已影响6人  279cb620c509

UIDatePicker一个自定义日期选择器获取日期数据的问题

前言:最近公司UI出了一个自定义UIDatePicker的选择器

自定义的UI简单,但是显示的日期数据还要自己算平闰年吗???

所以自己写了一个日期数据生产function

懒,写的很粗糙

(from: currentYear! - 80, through: currentYear)81年的,其他年随意改吧

func getDaysInMonth( year: Int, month: Int) -> Int
{
    let calendar = Calendar.current

    var startComps = DateComponents()
    startComps.day = 1
    startComps.month = month
    startComps.year = year

    var endComps = DateComponents()
    endComps.day = 1
    endComps.month = month == 12 ? 1 : month + 1
    endComps.year = month == 12 ? year + 1 : year

    let startDate = calendar.date(from: startComps)
    let endDate = calendar.date(from:endComps)

    let diff = calendar.dateComponents([.day], from: startComps, to: endComps)
    return diff.day!
}
//
//getDaysInMonth(year: 2019, month: 4)

    struct Year {
        let name: String
        let months: [Month]
    }

    struct Month {
        let name: String
        let days: [String]
    }

var subdivisionsData: [Year] = {

        var localData : [[String: [[String: [String]]]]] =  [[String: [[String: [String]]]]]()
    let currentYear = Calendar.current.dateComponents(in: TimeZone(identifier:"Asia/Shanghai")!, from: Date()).year
        var years : [Year] = [Year]()
    for year in stride(from: currentYear! - 80, through: currentYear!, by: 1) {
            var days : [String] = [String]()
            var months : [Month] = [Month]()
            defer{
                years.append(Year.init(name: String(format: "%d", year), months: months))
            }
            for month in 1...12 {
                defer{
                    months.append( Month.init(name: String(format: "%d", month), days: days)  )
                    days.removeAll()
                }
                for day in 1...getDaysInMonth(year: year, month: month) {
                    days.append(String(format: "%d", day))
                }
            }

        }

        return years

    }()

print(subdivisionsData[0])
上一篇下一篇

猜你喜欢

热点阅读