通過(guò)Calendar實(shí)現(xiàn)日期加減。
主要是通過(guò)DateComponents組件設(shè)置要加減的年月日
下面舉幾個(gè)例子
- 獲取上一天
extension Date {
func kk_lastDay() -> Date? {
//.gregorian代表公歷
let calendar = Calendar(identifier: .gregorian)
var components = calendar.dateComponents([.year, .month, .day], from: self)
/*
* value是int型,component對(duì)應(yīng)dateComponents(上一行代碼)設(shè)置,
* 設(shè)置了year,month,day中的哪個(gè)就設(shè)置哪個(gè)
* value負(fù)數(shù)代表向前推幾年,幾月,幾天,正數(shù)代表向后推幾年,幾月,幾天。按需設(shè)置
*/
components.setValue(0, for: .year)
components.setValue(0, for: .month)
components.setValue(-1, for: .day)
let lastDay = calendar.date(byAdding: components, to: self)
return lastDay
}
}
- 獲取下一個(gè)月(Components也可以只設(shè)置其中一個(gè),按需求來(lái))
func kk_nextMonth() -> Date? {
//.gregorian代表公歷
let calendar = Calendar(identifier: .gregorian)
var components = calendar.dateComponents([.month], from: self)
/*
* components只用了.month來(lái)生成,所以只設(shè)置month的值就好了
* 這里是獲取下一個(gè)月,所以.month的value = 1,如果是上兩個(gè)個(gè)月value = -2
*/
components.setValue(1, for: .month)
let nextMonth = calendar.date(byAdding: components, to: self)
return nextMonth
}