swift根據(jù)當(dāng)前時間獲取一周時間
func GetWeeksDate() -> [Date]? {
//當(dāng)前時間
let currentDate = Date()
let calender = Calendar.current
var comp = calender.dateComponents([.year, .month, .day, .weekday], from: currentDate)
//當(dāng)前時間是幾號、周幾
let currentDay = comp.day
let weeKDay = comp.weekday
//如果獲取當(dāng)前時間的日期和周幾失敗嘶摊,返回nil
guard let day = currentDay, let week = weeKDay else {
return nil
}
//由于1代表的是周日延蟹,因此計算出準(zhǔn)確的周幾
var currentWeekDay = 0
if week == 1 {
currentWeekDay = 7
} else {
currentWeekDay = week - 1
}
//1 ... 7表示周一到周日
//進(jìn)行遍歷和currentWeekDay進(jìn)行比較,計算出之間的差值叶堆,即為當(dāng)前日期和一周時間日期的差值阱飘,即可計算出一周時間內(nèi)準(zhǔn)備的日期
var dates: [Date] = []
for index in 1 ... 7 {
let diff = index - currentWeekDay
comp.day = day + diff
let date = calender.date(from: comp)
//由于上述方法返回的Date為可選類型,要進(jìn)行判空處理
if let _ = date {
dates.append(date!)
}
}
//返回時間數(shù)組
return dates
}
和朋友聊天中談到有個需求需要一周內(nèi)的時間虱颗,因此就找了下資料沥匈,自己寫了下。具體使用要結(jié)合自己的需求環(huán)境忘渔,思想是相通的高帖。如有遺漏,還望指正畦粮。