根据开始日期和给定周数获取周范围

时间:2020-07-12 20:58:34

标签: swift

我的开始日期为2020年7月13日,一个整数表示我选择的星期数,在本例中为5。我想打印那五个星期的每周范围。预期输出示例:

  1. 7月13日-7月19日
  2. 7月20日至7月26日
  3. 7月27日-8月2日
  4. 8月3日-8月9日
  5. 8月10日-8月16日

使用下面的代码,我可以得到前两周,不过,根据周的输入,应该继续打印周。

func getRanges() {
    let arrWeekDates = rangeString!.getWeekDates() // Get dates of two weeks.
    let dateFormat = "MMM dd"
    let thisMon = arrWeekDates.thisWeek.first!.toDate(format: dateFormat)
    let thisSun = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 1].toDate(format: dateFormat)

    let nextMon = arrWeekDates.nextWeek.first!.toDate(format: dateFormat)
    let nextSun = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 1].toDate(format: dateFormat)

    print("This Week: \(thisMon) - \(thisSun)")
    print("Next Week: \(nextMon) - \(nextSun)")
    
}

extension Date {

func getWeekDates() -> (thisWeek:[Date],nextWeek:[Date]) {
        var tuple: (thisWeek:[Date],nextWeek:[Date])
        var arrThisWeek: [Date] = []
        for i in 0..<7 {
            arrThisWeek.append(Calendar.current.date(byAdding: .day, value: i, to: startOfWeek)!)
        }
        var arrNextWeek: [Date] = []
        for i in 1...7 {
            arrNextWeek.append(Calendar.current.date(byAdding: .day, value: i, to: arrThisWeek.last!)!)
        }
        tuple = (thisWeek: arrThisWeek,nextWeek: arrNextWeek)
        return tuple
    }

var startOfWeek: Date {
            let gregorian = Calendar(identifier: .gregorian)
            let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
            return gregorian.date(byAdding: .day, value: 1, to: sunday!)!
        }
func toDate(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
   }

1 个答案:

答案 0 :(得分:0)

我创建了一个函数,该函数以开始日期和星期数为参数,并返回DateInterval的数组作为星期开始和结束日期

func weeks(from date: Date, duration: Int) -> [DateInterval]? {
    let calendar = Calendar.current

    //Get date for first day of the week
    let diff = calendar.component(.weekday, from: date) - calendar.firstWeekday
    guard let firstDate = calendar.date(byAdding: .day, value: -(diff < 0 ? 7 + diff : diff), to: date) else {
        return nil
    }

    //Generate start and end date for the duration 
    var weeks = [DateInterval(start: firstDate, end: calendar.date(byAdding: .day, value: 6, to: firstDate)!)]
    for week in 1..<duration {
        guard let firstDayOfWeek = calendar.date(byAdding: .day, value: 7, to: weeks[week - 1].start),
            let lastDayOfWeek = calendar.date(byAdding: .day, value: 6, to: firstDayOfWeek) else { return nil }

        weeks.append(DateInterval(start: firstDayOfWeek, end: lastDayOfWeek))
    }
    return weeks
}

并使用它并打印您可以做的日期

if let weeks = weeks(from: Date(), duration: 5) {
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM dd"

    for interval in weeks {
        print("\(formatter.string(from: interval.start)) -  \(formatter.string(from: interval.end))")
    }
}

输出

7月13日-7月19日
7月20日至7月26日
7月27日-8月2日
八月03-八月09
8月10日-8月16日