Get a Week From a Different Starting Day

筅森魡賤 提交于 2019-12-11 03:57:32

问题


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:


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


来源:https://stackoverflow.com/questions/25152239/get-a-week-from-a-different-starting-day

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!