0

My goal is to get the start date and end date of the week. So i found: https://stackoverflow.com/a/46402722/4757272 which was a pretty neat solution. I however have some issues. Trying it out, the variable called sunday is actually an saturday when i look in the calendar, thats pretty disturbing, but here comes the really disturbing part:

Playground image

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)
    }
}

dump(Date().startOfWeek)
dump(Date().endOfWeek)

As you can see i print the result and as smooth as playground is it shows me the result in the right tab as well. However they are different dates.. so which one should i rely on?

Vollan
  • 1,887
  • 11
  • 26
  • 1
    Please copy and paste code and output as text into your question. Pictures are too hard to read and pictures can't be searched or referenced. – rmaddy May 02 '19 at 05:08
  • Please understand the difference between UTC and local time and you will see that the dates are the same. – rmaddy May 02 '19 at 05:10
  • @rmaddy Done, i thought it wouldn't be needed since i needed to show the console / right tab, but you are right :) – Vollan May 02 '19 at 05:10
  • @rmaddy so when i collect Date() its in UTC and when i print it it becomes UTC+2 (local)? – Vollan May 02 '19 at 05:13
  • Printing a date (via `dump`) shows UTC. But the playground (on the right) shows it in locale time. There's nothing wrong. Just two different representations of the same value. – rmaddy May 02 '19 at 05:14

0 Answers0