简体   繁体   中英

Get all dates for current week returns incorrect if the date is beginning of a month

This is a code i found online to get all dates for the current week based on today´s date. If the date is the beginning of the month, for example Thursday September 01 2016 then it starts the week from Thursday and end the week at Wednesday September 07 2016 . This is really bothering me because if the date is the end of the month; Sunday July 31 2016 then it will start on Monday and end on Sunday in that week which is exactly what i want.

This might be a duplicate but i spent a while looking at similar questions and i am still stuck.

Edit: Is there a way to return all date for the current week based on the current date?(And if you have time, the next week as well?)

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
    }


}

This solution checks if the current date is Monday.

If yes , it's the beginning of the week, if no , get back to the past Monday.

It uses also the formatDate function.

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
}

I don't know if there's an actual question here, but I wrote up a quick snippet that will always give you the Sunday of the current week:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM