简体   繁体   English

如果日期是一个月初,则获取当前星期的所有日期均不正确

[英]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 . 如果日期是月份的开始,例如2016年9月1日星期四,那么它将从星期四开始一周,到2016年9月7日星期三结束一周。 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. 2016年7月31日(星期日),然后它将在星期一开始,在该周的星期日结束,这正是我想要的。

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. 它还使用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
}

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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