Swift 判断两个日期是否是同一个星期
方法一:
func isSameWeek() {
let dateformatter = DateFormatter.init()
dateformatter.dateFormat = "yyy-MM-dd"
let fromDate = dateformatter.date(from: "2019-2-28")
let fromWeek = self.getweekDayWithDate(fromDate!)
let currentWeek = self.getweekDayWithDate(Date())
let betwwen = self.daysBetweenDate(fromDate: fromDate!)
if betwwen >= 7 {
//show
print("show")
}else {
if fromWeek >= currentWeek {
//show
print("show")
}else {
//hidden
print("hidden")
}
}
}
//确定当前x是星期几
func getweekDayWithDate(_ date : Date) ->Int{
//日 一 二 三 四 五 六
//1 2 3 4 5 6 7
let calensar : Calendar = Calendar.current
let com = calensar.component(Calendar.Component.weekday, from: date)
print("----\(com)")
return com
}
func daysBetweenDate(fromDate: Date) -> Int {
let components = Calendar.current.dateComponents([Calendar.Component.day], from: fromDate, to: Date())
return components.day ?? 0
}
上边的发放有些绕,可以参考做其他类似的判断,之后有了一个简单的方法就是:
方法二:
func isSameWeek () -> Bool {
let currentWeekOfYear = getWeekOfYear(date: Date.init())
if let saveWeekOfYear = UserDefaults.standard.object(forKey: "popWeekOfYear") as? Int{
if saveWeekOfYear == currentWeekOfYear {
return false
}else {
UserDefaults.standard.set(currentWeekOfYear, forKey: "popWeekOfYear")
return true
}
}else {
UserDefaults.standard.set(currentWeekOfYear, forKey: "popWeekOfYear")
return true
}
}
func getWeekOfYear(date: Date) -> Int {
let components = Calendar.current.dateComponents([Calendar.Component.weekOfYear], from: date)
return components.weekOfYear ?? 0
}
自己原创 贴出来共享,转载请注明出处。。。(^-^)