How to calculate the number of working days between two dates?

A friend asked me yesterday if this is possible on the iPhone. I looked at NSCalendar and all related classes, but could not find a solution to this.

So, I thought about this: if I had two dates, dateA and dateB, I would have to do a for loop and a loop every day in this interval. Then I will count the working days of Monday to Friday and return the result.

Then I went to bed, and I woke up with this probably much better idea: I need to know what day it is when I start. Let's say it on Thursday. And then I have to know how many days are in this interval. The last part is not hard to understand. For the first part, I don’t have a hint yet, but I think that in NSCalendar there is a week week value. With this, I could do some simple math to calculate the number of working days.

Has anyone done this already on the iPhone?

+3
source share
2 answers

How many times do you perform this calculation? Should the dates you need fall within a certain range?

, , . , , . ... , - " ", - .

+2

, :

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

// Determine the integer number of weeks between the two dates
NSDateComponents *components = [calendar components:NSWeekCalendarUnit fromDate:firstDate toDate:secondDate options:0];
NSInteger numWeeks = [components week];

// Determine the day of the week for each date
components = [calendar components:NSWeekdayCalendarUnit fromDate:firstDate];
NSInteger firstWeekday = [components weekday];
components = [calendar components:NSWeekdayCalendarUnit fromDate:secondDate];
NSInteger secondWeekday = [components weekday];

[calendar release];

, , .

+2

Source: https://habr.com/ru/post/1739794/


All Articles