How to get start and end of the week in swift ? this is my code
extension Date {
var startOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 1, to: sunday)
}
var endOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 7, to: sunday)
}
}
i am calling like this
let startWeek = Date().startOfWeek
let endWeek = Date().endOfWeek
print(startWeek!)
print(endWeek!)
var dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "dd-MM-yy"
let startWeek2 = dateFormat1.string(from: startWeek!)
var dateFormat12 = DateFormatter()
dateFormat12.dateFormat = "dd-MM-yy"
let endWeek2 = dateFormat12.string(from: endWeek!)
print(startWeek2)
print(endWeek2)
and output
2017-09-24 18:30:00 +0000
2017-09-30 18:30:00 +0000
25-09-17
01-10-17
Your code is working perfectly fine. If you would run your code in a Playground, you could see the actual Date
objects rather than there String representations. Even if you don't specify a DateFormatter
, under the hood, when doing print(Date())
, Swift uses a DateFormatter
to print Date
objects and hence that value will be a relative time instead of the absolute point in time provided by the Date
object.
In a Playground you can see that the actual startOfWeek
is "Sep 25, 2017 at 12:00 AM"
, while the endOfWeek
is "Oct 1, 2017 at 12:00 AM"
, which are the correct values for the current week.
Don't use print(Date())
for checking the correctness of Date
objects, since as you can see, it will yield unexpected results due to the underlying DateFormatter
s used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With