Noah Iarrobino
Noah Iarrobino

Reputation: 1543

Get last 7 and next 7 days in date format in swift

I am trying to fill an array of type Date with 15 values, today, the 7 days prior, and the next 7 days. I'm having a hard time figuring out how to get the date. I tried implementing it like this:

func setupDates(){
        //get date of 7 days prior to right now
        for i in 1...15 {
            //add a day per iteration
            //append date to date array
        }
    }

Upvotes: 1

Views: 1626

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

I would suggest having a look at Calendar

It can be a little cumbersome, but generally has a lot of power to it

So you might do something like...

let anchor = Date()
let calendar = Calendar.current

let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .long
for dayOffset in -7...7 {
    if let date = calendar.date(byAdding: .day, value: dayOffset, to: anchor) {
        print(formatter.string(from: date))
    }
}

nb: This was a simple playground test

Which will print something like...

October 1, 2021 at 10:22:05 AM GMT+10
October 2, 2021 at 10:22:05 AM GMT+10
October 3, 2021 at 10:22:05 AM GMT+11
October 4, 2021 at 10:22:05 AM GMT+11
October 5, 2021 at 10:22:05 AM GMT+11
October 6, 2021 at 10:22:05 AM GMT+11
October 7, 2021 at 10:22:05 AM GMT+11
October 8, 2021 at 10:22:05 AM GMT+11
October 9, 2021 at 10:22:05 AM GMT+11
October 10, 2021 at 10:22:05 AM GMT+11
October 11, 2021 at 10:22:05 AM GMT+11
October 12, 2021 at 10:22:05 AM GMT+11
October 13, 2021 at 10:22:05 AM GMT+11
October 14, 2021 at 10:22:05 AM GMT+11
October 15, 2021 at 10:22:05 AM GMT+11

nb: Today is the 8th nbb: Your question title says "date format", but you're just trying to fill an array with Dates. The basic concept will work either way

Upvotes: 4

Related Questions