-1

Building a MacOS app.

Not sure where this is going off the rails. I am trying to get the start and end of the week (Sunday/Saturday) and am using this function:

func getStartAndEndOfWeek(_ dateToCheck:Date) {
        
        //vars
        var sundayDiff = 0
        var saturdayDiff = 0
        
        //set up a date formatter
        var formatter:DateFormatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "YYYY-MM-DD"
        
        //get day of this startDate
        let calendar = Calendar.current
        let dayComponents = calendar.dateComponents([.weekday], from: Date())
        if let dayOfWeek = dayComponents.weekday {
            sundayDiff = dayOfWeek - 1
            saturdayDiff = 7 - dayOfWeek
        }
        
        //get sunday as date
        let sunday:Date = Calendar.current.date(byAdding: .day, value: -1 * sundayDiff, to: dateToCheck)!
        let saturday:Date = Calendar.current.date(byAdding: .day, value: saturdayDiff, to: dateToCheck)!
        
        let strSunday = formatter.string(from: sunday)
        
        
    }

printing sunday gives me the correct date (current date is Wednesday, March 30, 2022):

2022-03-27 15:36:45 +0000

converting sunday to a string gives me a day of 86

2022-03-86

What am I doing wrong?

PruitIgoe
  • 6,166
  • 16
  • 70
  • 137
  • 1
    Format place holder letters are case sensitive. Always refers to the documentation: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns – Larme Mar 30 '22 at 15:55

2 Answers2

3

The correct syntax is:

formatter.dateFormat = "yyyy-MM-dd"

Lower or upper case matters here.

HunterLion
  • 3,496
  • 1
  • 6
  • 18
1

The issue there is that D uppercased means the day of the year not the day of the month. Note also that Y uppercased is for yearForWeekOfYear.

If you need further reference you can check this

enter image description here

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571