swift根据当前时间获取一周时间
func GetWeeksDate() -> [Date]? {
//当前时间
let currentDate = Date()
let calender = Calendar.current
var comp = calender.dateComponents([.year, .month, .day, .weekday], from: currentDate)
//当前时间是几号、周几
let currentDay = comp.day
let weeKDay = comp.weekday
//如果获取当前时间的日期和周几失败,返回nil
guard let day = currentDay, let week = weeKDay else {
return nil
}
//由于1代表的是周日,因此计算出准确的周几
var currentWeekDay = 0
if week == 1 {
currentWeekDay = 7
} else {
currentWeekDay = week - 1
}
//1 ... 7表示周一到周日
//进行遍历和currentWeekDay进行比较,计算出之间的差值,即为当前日期和一周时间日期的差值,即可计算出一周时间内准备的日期
var dates: [Date] = []
for index in 1 ... 7 {
let diff = index - currentWeekDay
comp.day = day + diff
let date = calender.date(from: comp)
//由于上述方法返回的Date为可选类型,要进行判空处理
if let _ = date {
dates.append(date!)
}
}
//返回时间数组
return dates
}
和朋友聊天中谈到有个需求需要一周内的时间,因此就找了下资料,自己写了下。具体使用要结合自己的需求环境,思想是相通的。如有遗漏,还望指正。