如果日期是一个月的开始,则获取当前周的所有日期返回错误

时间:2016-07-27 20:43:35

标签: ios swift date

这是我在网上找到的代码,用于根据今天的日期获取当前周的所有日期。如果日期是月初,例如 2016年9月1日星期四,则从星期四开始一周,并在 2016年9月7日星期三结束一周< / strong>即可。这真让我烦心,因为如果日期是月末; 2016年7月31日星期日然后它会在星期一开始,并在那周的星期日结束,这正是我想要的。

这可能是重复但我花了一段时间看着类似的问题,我仍然卡住了。

修改 有没有办法根据当前日期返回当前周的所有日期?(如果你有时间,下周还有?)

func formatDate(date: NSDate) -> String {
    let format = "EEEE MMMM dd yyyy"
    let formatter = NSDateFormatter()
    formatter.dateFormat = format
    return formatter.stringFromDate(date)

}
// =======================================================================//
//                 THIS WEEK DATES                                        //
// =======================================================================//
func formattedDaysInThisWeek() -> [String] {
    // create calendar
    let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!

    // today's date
    let today = NSDate()
    let todayComponent = calendar.components([.Day, .Month, .Year], fromDate: today)
    let components = calendar.components([.Weekday], fromDate: today)



    // range of dates in this week
    let thisWeekDateRange = calendar.rangeOfUnit(.Day, inUnit:.WeekOfMonth, forDate:today)


    // date interval from today to beginning of week
    let dayInterval = thisWeekDateRange.location - todayComponent.day
    print(thisWeekDateRange.location)
    print(todayComponent.day)


    // date for beginning day of this week, ie. this week's Sunday's date

    if components.weekday == 1 {
        print("Is a sunday")
        let beginningOfWeek = calendar.dateByAddingUnit(.Day, value: -6, toDate: today, options: .MatchNextTime)

        var formattedDays: [String] = []

        for i in 0 ..< 7 {
            let date = calendar.dateByAddingUnit(.Day, value: i, toDate: beginningOfWeek!, options: .MatchNextTime)!
            formattedDays.append(formatDate(date))

        }
        return formattedDays
    } else {
        print("Not a sunday")
        let beginningOfWeek = calendar.dateByAddingUnit(.Day, value: dayInterval, toDate: today, options: .MatchNextTime)

        var formattedDays: [String] = []

        for i in 1 ..< thisWeekDateRange.length + 1 {
            let date = calendar.dateByAddingUnit(.Day, value: i, toDate: beginningOfWeek!, options: .MatchNextTime)!
            formattedDays.append(formatDate(date))

        }

        return formattedDays
    }


}

2 个答案:

答案 0 :(得分:2)

此解决方案检查当前日期是否为星期一。

如果,那就是本周的开始,如果,请回到过去的星期一。

它还使用formatDate函数。

func formattedDaysInThisWeek() -> [String] {
    // create calendar
    let calendar = Calendar(identifier: .gregorian)

    // today's date
    let today = Date()

    let weekday = calendar.component(.weekday, from: today)
    let beginningOfWeek : Date
    if weekday != 2 { // if today is not Monday, get back
        let weekDateConponent = DateComponents(weekday: 2)
        beginningOfWeek = calendar.nextDate(after: today, matching: weekDateConponent, matchingPolicy: .nextTime, direction: .backward)!

    } else { // today is Monday
        beginningOfWeek = calendar.startOfDay(for: today)
    }
    var formattedDays = [String]()
    for i in 0..<7 {
        let date = calendar.date(byAdding: .day, value: i, to: beginningOfWeek)!
        formattedDays.append(formatDate(date))
    }
    return formattedDays
}

答案 1 :(得分:0)

我不知道这里是否有实际的问题,但我写了一个快速片段,总是会给你本周的星期日:

let today = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let todayComps = calendar.components([.Day, .Month, .Year], fromDate: today)
let dayOfWeekComps = calendar.components([.Weekday], fromDate: today)
todayComps.day -= (dayOfWeekComps.weekday - 1)
let sunday = calendar.dateFromComponents(todayComps)