美文网首页
获取当前时间 一周的 日期

获取当前时间 一周的 日期

作者: Ame___ | 来源:发表于2019-12-03 14:00 被阅读0次
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
    }

相关文章

网友评论

      本文标题:获取当前时间 一周的 日期

      本文链接:https://www.haomeiwen.com/subject/hrucgctx.html