实现的功能:
1. 获取当前日期的年、月、日
2. 获取指定月份的天数
import Foundation
class FormatTime24 {
var year: Int?
var month: Int?
var day: Int?
}
extension Date {
// MARK: 获取当前年 月 日
static var now: FormatTime24 {
get {
let n = FormatTime24()
let date = Date()
let calendar = Calendar.current
n.year = calendar.component(.year, from: date)
n.month = calendar.component(.month, from: date)
n.day = calendar.component(.day, from: date)
return n
}
}
// MARK: 获取指定年月 月份的天数
static func getDaysInMonth(year: Int, month: Int) -> Int {
var startComps = DateComponents()
startComps.year = year
startComps.month = month
startComps.day = 1
var endComps = DateComponents()
endComps.year = year
endComps.month = month + 1
if month == 12 {
endComps.year = year + 1
endComps.month = 1
}
endComps.day = 1
let calendar = Calendar.current
let dayRange = calendar.dateComponents([.day], from: startComps, to: endComps)
return dayRange.day ?? 0
}
}