2
votes

Before I try this with my approach (which I have a feeling is simplistic and too drawn out), I wanted to ask anyone if there is an easier / more direct way in Swift.

The task is to let the user pick any day in the calendar. So let's say they pick Tuesday a month ago. Now I want to put that entire week into an array. So the Monday before, then Tues, then Wednesday, Thurs, Fri, Sat, Sun. So the array would always hold 7 days.

Here is the thing - I'd like to change this up so the user can define what their "start day" is - for example if I assign Thursday as my starting day, then if I were to pick a random Tuesday again from a few months back, the array should look like this: [Thurs/Fri/Sat/Sun/Mon/Tues/Wed] (the array always starts with the user's starting day) and will go backwards a week if you pick a date before your start date. So for example if I selected Tuesday the 14, then it would go back to the Thursday the 9th as the starting day.

My approach was to simply do a loop, starting from the day the user specifies, and walking backwards until I've reached my start date, and then walk forwards until I hit the corresponding end date.

Is there a better approach instead of doing something like that? Maybe some nifty NSDateComponents i'm not ware of or some such?

Thanks for your help as always!

1
What if you pick the day after your starting day - so if the starting day is Thursday and you pick a friday - do you want the week from the Thursday the day before the selected day or from the next Thursday i.e. after the selected day?Paulw11

1 Answers

2
votes

You can set the firstWeekday property of the current calendar to determine the first day of the week for all calendrical calculations:

let cal = NSCalendar.currentCalendar()
cal.firstWeekday = 5 // 1 == Sunday, 5 == Thursday

Use rangeOfUnit to determine the start and of the week containing the chosen date:

let chosenDate = ...
var startOfWeek : NSDate? = nil
var lengthOfWeek : NSTimeInterval = 0
cal.rangeOfUnit(.WeekCalendarUnit, startDate: &startOfWeek, interval:&lengthOfWeek, forDate: chosenDate)
var endOfWeek = startOfWeek!.dateByAddingTimeInterval(lengthOfWeek)

Iterate over the dates:

var date = startOfWeek!
let formatter = NSDateFormatter()
formatter.dateFormat = "EEEE, dd.MM.yyyy"

while date.compare(endOfWeek) == NSComparisonResult.OrderedAscending  {
    println(formatter.stringFromDate(date))
    date = cal.dateByAddingUnit(.DayCalendarUnit, value: 1, toDate: date, options: NSCalendarOptions(0))
}

Example output (for today as the chosen date):

Thursday, 31.07.2014
Friday, 01.08.2014
Saturday, 02.08.2014
Sunday, 03.08.2014
Monday, 04.08.2014
Tuesday, 05.08.2014
Wednesday, 06.08.2014