First day of the week Date Renewal

I wrote an extension Datethat returns the first day of the week for a given date (Mondays count on the first day). However, he continues to return one Monday too early. Here is my code:

extension Date {
    func startOfWeek() -> Date {
        var cal = Calendar.current
        var component = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
        cal.firstWeekday = 2
        return cal.date(from: component)!
    }
}

So, when I give him the following date:

let sampleDate = "2017-06-15 02:50:09 +0000"

let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
    if let date = formatter.date(from: sampleDate) {
        print(date.startOfWeek())
    }
}

2017-06-05 07:00:00 +0000 prints out.

Can someone help me figure out why my code returns a weekly date too soon?

+4
source share
1 answer

A calendar calculation must be added to the object Calendar(exactly the same as startOfDay(for: )). If you insist on making it an extension for Date, you can adapt the code below:

extension Calendar {
    func startOfWeek(for date: Date) -> Date {
        if self.component(.weekday, from: date) == 2 {
            return self.startOfDay(for: date)
        } else {
            let components = DateComponents(calendar: self, weekday: 2)
            return self.nextDate(after: date, matching: components, matchingPolicy: .nextTime, direction: .backward)!
        }
    }
}

// Test: 2017-06-15 02:50:09 in your **local time**
let date = DateComponents(calendar: .current, year: 2017, month: 6, day: 15, hour: 2, minute: 50, second: 9).date!

// My timezone is EDT
print(Calendar.current.startOfWeek(for: date)) // 2017-06-12 04:00:00 +0000

, . - . . , .

+1

Source: https://habr.com/ru/post/1674943/


All Articles