/// 获取当前日期 所在的周
func getWeekTime(_ dateStr: String) -> Array<String> {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd"
let nowDate = dateFormatter.date(from: dateStr)
let calendar = Calendar.current
let comp = calendar.dateComponents([.year, .month, .day, .weekday], from: nowDate!)
// 获取今天是周几
let weekDay = comp.weekday
// 获取几天是几号
let day = comp.day
// 计算当前日期和本周的星期一和星期天相差天数
var firstDiff: Int
var lastDiff: Int
// weekDay = 1;
if (weekDay == 1) {
firstDiff = -6;
lastDiff = 0;
} else {
firstDiff = calendar.firstWeekday - weekDay! + 1
lastDiff = 8 - weekDay!
}
// 在当前日期(去掉时分秒)基础上加上差的天数
var firstDayComp = calendar.dateComponents([.year, .month, .day], from: nowDate!)
firstDayComp.day = day! + firstDiff
let firstDayOfWeek = calendar.date(from: firstDayComp)
var lastDayComp = calendar.dateComponents([.year, .month, .day], from: nowDate!)
lastDayComp.day = day! + lastDiff
let lastDayOfWeek = calendar.date(from: lastDayComp)
let firstDay = dateFormatter.string(from: firstDayOfWeek!)
let lastDay = dateFormatter.string(from: lastDayOfWeek!)
let weekArr = [firstDay, lastDay]
return weekArr;
}
网友评论