Convert the for loop to accept ID type - objective-c

I want to be able to reuse this method so it's not restricted by the class being called in the for loop declaration.
The problem is the compiler has no idea what id actually is, so I cannot use . notation on it. I need to cast it to a whatever type of event class i'll be passing it, instead of having to repeat the method for SpecialEvent1 SpecialEvent2 SpecialEvent3
So instead of for (SpecialEvent1 *event in day) I want to be able to do something like for (id event in day) but problem occurs when I try to access the time or duration property
- (NSArray *)sumDay:(NSArray *)day {
NSInteger morning = 0, afternoon = 0, evening = 0, night = 0;
for (SpecialEvent1 *event in day) {
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:event.time];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:date];
NSInteger hour = [components hour];
if (hour < 12) {
morning += event.duration;
}
else if (hour < 18) {
afternoon += event.duration;
}
else if (hour < 20) {
evening += event.duration;
}
else {
night += event.duration;
}
}
NSArray *sums = #[#(morning), #(afternoon), #(evening), #(night)];
return sums;
}

Assuming that you aren't interested in objects that don't have a time or duration property, you could define a protocol which says this:
#protocol TimedEvent <NSObject>
-(NSTimeInterval)time;
-(NSTimeInterval)duration;
#end
Then go through the array like this:
- (NSArray *)sumDay:(NSArray *)day {
NSInteger morning = 0, afternoon = 0, evening = 0, night = 0;
for (id<TimedEvent> event in day) {
if (![event conformsToProtocol:#protocol(TimedEvent)]) {
continue;
}
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:event.time];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:date];
NSInteger hour = [components hour];
if (hour < 12) {
morning += event.duration;
}
else if (hour < 18) {
afternoon += event.duration;
}
else if (hour < 20) {
evening += event.duration;
}
else {
night += event.duration;
}
}
NSArray *sums = #[#(morning), #(afternoon), #(evening), #(night)];
return sums;
}

Related

Compare time in objective c

I want to compare different times of outlets with ipad current time so what i did was this
if(CT!=nil && startTime!=nil &&endTime!=nil)
{
/* If current time is greater than begin time but less than end time then he can give feedack
*/
if (([CT compare:startTime]== NSOrderedDescending) && ([CT compare:endTime]== NSOrderedAscending) ) {
return YES;
}
else if (([CT compare:startTime]== NSOrderedSame) || ([CT compare:endTime]== NSOrderedSame))
{
return YES;
}
else if (([CT compare:startTime]== NSOrderedDescending) && ([CT compare:endTime]== NSOrderedDescending))
{
return NO; // out of outlet timings
}
This seems to be working good till now but when i change the outlet time to
start time = 18:30PM
end time = 2:00 AM
Then in that case the above code fails, when the ipad clocks at 1:00AM then the first if condition fails so i added this code below
if (([CT compare:startTime]== NSOrderedAscending) && ([CT compare:endTime]== NSOrderedAscending))
{
}
Now as a developer i am sure that if the device clocks at 1:00 AM then it wont fail but what if somebody updated the outlet timing to
start time = 9:00AM
end time = 11:00 AM
and current device time = 8:00 AM
then in the above case my the second code will fail.
what i want is some suggestion as in what i can do in the second if condition
Code that creates CT is :
NSDate *sysDate = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"HH:mm:ss"];
NSString *timeString = [df stringFromDate:sysDate];
NSDate *CT = [df dateFromString:timeString];
startTime and endTime are date objects stored in the plist.
Rewrite your conditions as if there were numbers instead of dates and see what they actually do (NSOrderedDescending becomes > "greater than", NSOrderedAscending becomes < "less than"):
if (ctNumber > startNumber && ctNumber < endNumber)
{ ... }
else if (ctNumber == startNumber || ctNumber == endNumber)
{ ... }
else if (ctNumber > startNumber && ctNumber > endNumber)
{ ... }
I hope this way it's obvious the last one is not what you mean at all, and the other condition you tried later was still incorrect. The correct one is (ctNumber < startNumber || ctNumber > endNumber) which is exactly what standalone else would do, so you can just drop it:
if (ctNumber > startNumber && ctNumber < endNumber)
{ ... }
else if (ctNumber == startNumber || ctNumber == endNumber)
{ ... }
else
{ /* otherwise ; everything else ; in all other cases */ ... }
But you really should follow #ILYA2606 advice and compare time intervals (which are numbers) in future to avoid further confusions like this. It will also allow you to use <= and >= and so drop the middle condition:
NSTimeInterval ctNumber = [CT timeIntervalSince1970];
NSTimeInterval startNumber = [startDate timeIntervalSince1970];
NSTimeInterval endNumber = [endDate timeIntervalSince1970];
BOOL ctLiesInsideInterval = (ctNumber >= startNumber && ctNumber <= endNumber);
return ctLiesInsideInterval;
And finally, I have to point out that the date formatter code that creates CT is nonsense and is equivalent to simply using current time:
NSDate* CT = [NSDate date];
Convert NSString to NSDate, compare timeIntervals:
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"HH:mm:ss"];
NSDate *CTDate = [df dateFromString:CT];
NSDate *startDate = [df dateFromString:startTime];
NSTimeInterval CTInterval = [CTDate timeIntervalSince1970];
NSTimeInterval startInterval = [startDate timeIntervalSince1970];
NSTimeInterval deltaInterval = startInterval - CTInterval;
if(deltaInterval < 0){
//Ascending (CT < startTime)
}
else if(deltaInterval > 0){
//Descending (CT > startTime)
}
else{
//Some (CT = startTime)
}
Try this one..
NSDate *currentDate=[NSDate date];
NSTimeInterval daysInSeconds = 60*60;
NSDate *starttime= [currentDate dateByAddingTimeInterval:daysInSeconds];
daysInSeconds = 2*60*60;
NSDate *endtime= [currentDate dateByAddingTimeInterval:daysInSeconds];
if( [starttime compare:currentDate]==NSOrderedAscending ){
//Ascending (CT < startTime)
}
if( [starttime compare:currentDate]==NSOrderedDescending ){
//Descending (CT > startTime)
}
if( [endtime compare:currentDate]==NSOrderedAscending ){
//Ascending (CT < endtime)
}
if( [endtime compare:currentDate]==NSOrderedDescending ){
//Descending (CT > endtime)
}

How do I subtract a duration from an NSDate, but not include the weekends?

Using today as an example, how do I determine which date it was, 230 workdays ago?
I know how to do it iteratively with a while loop checking date and subtracting 1 if it's a workday, but I'm wondering if there is a better method.
Also, let's take a Sunday 1 PM as an example, and subtract 3 work days and 2 hours from that time. First, it doesn't make sense to subtract work-time from weekends. So it would have to move the time to 23:59:59 of Friday, and then subtract those 3 days and 2 hours.
If it's a Monday at 1:30 AM, and I'm subtracting 5 days and 3 work-hours from that time, then the result should be Friday 22:30 PM of the previous week.
Code to test Kevin's method:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *dc = [[NSDateComponents new] autorelease];
dc.month = 12;
dc.day = 19;
dc.year = 2011;
dc.hour = 1;
dc.minute = 0;
dc.second = 0;
NSDate *date = [cal dateFromComponents:dc];
NSLog(#"%#", [date descriptionWithCalendarFormat:nil timeZone:nil locale:nil]);
date = dateBySubtractingWorkOffset(date, 0, 2);
NSLog(#"%#", [date descriptionWithCalendarFormat:nil timeZone:nil locale:nil]);
Output log:
2011-12-02 16:33:46.878 otest[7124:707] 2011-12-19 01:00:00 -0500
2011-12-02 16:33:47.659 otest[7124:707] 2011-12-18 23:00:00 -0500
It should never be 12-18, since that's a Sunday.
Figure out how long from the last weekend your date is, subtract that amount from both your date and your offset. Now you can divide your offset by 5 to figure out how many full weeks are in your offset, and then multiply that by 7 and subtract this new value from your date. Take your previous offset (the one you divided by 5) and mod it by 5, to get the number of remaining days. If it's greater than 0, subtract that offset + 2 (for the weekend) from your date.
Note, this assumes every single weekday is a workday. Corporate holidays tend to make that assumption invalid. If you need to handle holidays, you're in for a much tougher problem.
Update: Here's an attempt to fix David's code to actually express the idea here:
NSDate *dateBySubtractingWorkOffset(NSDate *date, NSUInteger days, NSUInteger hours) {
const int secsInHour = 60*60;
const int secsInDay = 24*secsInHour;
NSTimeInterval offset = days*secsInDay + hours*secsInHour;
NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
// figure out distance from last weekend
{
NSUInteger units = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit;
NSDateComponents *dc = [cal components:units fromDate:date];
if (dc.weekday == 1 || dc.weekday == 7) {
// we're in the weekend already. Let's just back up until friday
// and then we can start our calculations there
} else {
// figure out our offset from sunday 23:59:59
dc.day -= (dc.weekday - 1);
dc.weekday = 1;
dc.hour = 23;
dc.minute = 23;
dc.second = 23;
NSDate *sunday = [cal dateFromComponents:dc];
NSTimeInterval newOffset = [date timeIntervalSinceDate:sunday];
if (offset < newOffset) {
// our offset doesn't even go back to sunday, we don't need any calculations
return [date dateByAddingTimeInterval:-offset];
}
offset -= [date timeIntervalSinceDate:sunday];
// Now we can jump back to Friday with our new offset
}
// Calculate last friday at 23:59:59
dc.day -= (dc.weekday % 7 + 1);
dc.hour = 23;
dc.minute = 59;
dc.second = 59;
date = [cal dateFromComponents:dc];
}
// We're now set to Friday 23:59:59
// Lets figure out how many weeks we have
int secsInWorkWeek = 5*secsInDay;
NSInteger weeks = (NSInteger)trunc(offset / secsInWorkWeek);
offset -= weeks*secsInWorkWeek;
if (weeks > 0) {
// subtract that many weeks from the date
NSDateComponents *dc = [[NSDateComponents alloc] init];
dc.week = -weeks;
date = [cal dateByAddingComponents:dc toDate:date options:0];
[dc release];
}
// now we can just subtract our remaining offset from the date
return [date dateByAddingTimeInterval:-offset];
}
I haven't exhaustively test this, but it's based on some category methods I use regularly. To determine how many weekdays are between date1 and date2 (assumes date1 < date2), divide the return value of this function by 24*60*60 (the number of seconds in a day).
This splits the calculation into number of days before the first weekend, number of days after the last weekend and number of days in the intervening weeks. A weekend starts on Saturday at 00:00:00 hours and ends on Sunday at 23:59:59 hours. Typically you want to avoid assuming that a day has 24 hours in it, because there may be special cases associated with daylight savings time. So I recommend using NSCalendar to calculate time intervals when this is important. But that happens on weekends, so it is not significant for this case.
There are two methods here. The first returns the NSDate end date if you provide a start date and the number of working days (weekdays) you want to extend out to. (An earlier date is returned if the number of working days is negative.) The second returns the number of seconds that correspond to number of working days (including fractional days) between two given NSDate dates.
I tried to keep calculations within a timezone, but defaulted to the system timezone. (By the way, if you want to calculate with fractional days, change the weekdays parameter to a float. Or you may want to calculate using a parameter in seconds. If so, then also change the calculation of totalInterval in the first method. You won't have to convert to seconds. All subsequent calculations in that method are done in seconds.)
- (NSDate*) calculateWeekDaysEndDateFrom:(NSDate*)_date1 and:(int)weekdays {
NSTimeInterval dayInterval = 24*60*60;
NSTimeInterval totalInterval = dayInterval * (float) weekdays;
NSTimeInterval secondsBeforeWeekend;
NSTimeInterval secondsAfterWeekend;
NSTimeInterval secondsInInterveningWeeks;
int numberOfWeeks;
NSDate *dateOfFirstSaturdayMorning;
NSDate *dateOfLastSundayNight;
NSDate *finalDate;
if (weekdays >0) {
dateOfFirstSaturdayMorning = [_date1 theFollowingWeekend];
secondsBeforeWeekend = [dateOfFirstSaturdayMorning timeIntervalSinceDate:_date1];
numberOfWeeks = (int)((totalInterval - secondsBeforeWeekend)/(5.0 * dayInterval));
secondsInInterveningWeeks = 5 * (float)(numberOfWeeks * dayInterval);
secondsAfterWeekend = totalInterval - secondsBeforeWeekend - secondsInInterveningWeeks;
dateOfLastSundayNight = [[dateOfFirstSaturdayMorning dateByAddingDays:7*numberOfWeeks+2] dateByAddingTimeInterval:-1]; // move from saturday morning to monday morning, then back off 1 second
finalDate = [dateOfLastSundayNight dateByAddingTimeInterval:secondsAfterWeekend];
}
else {
dateOfLastSundayNight = [_date1 thePreviousWeekend];
secondsAfterWeekend = [date1 timeIntervalSinceDate:dateOfLastSundayNight];
numberOfWeeks = (int)((-totalInterval - secondsAfterWeekend)/(5.0 * dayInterval));
secondsInInterveningWeeks = 5 * (float)(numberOfWeeks * dayInterval);
dateOfFirstSaturdayMorning = [[dateOfLastSundayNight dateByAddingDays:-(7*numberOfWeeks+2)] dateByAddingTimeInterval:+1];
secondsBeforeWeekend = -totalInterval - secondsInInterveningWeeks - secondsAfterWeekend;
finalDate = [dateOfFirstSaturdayMorning dateByAddingTimeInterval:-secondsBeforeWeekend];
}
NSLog(#"dateOfFirstSaturdayMorning = %#", [dateOfFirstSaturdayMorning descriptionWithLocale:[NSLocale currentLocale]]);
NSLog(#"dateOfLastSundayNight = %#",[dateOfLastSundayNight descriptionWithLocale:[NSLocale currentLocale]]);
NSLog(#"date 1 = %#", date1);
NSLog (#"daysBeforeWeekend = %.2f", secondsBeforeWeekend/((float)dayInterval));
NSLog (#"daysBetweenWeekends = %.2f", secondsInInterveningWeeks/((float)(dayInterval)));
NSLog (#"daysAfterWeekend = %.2f", secondsAfterWeekend/((float)dayInterval));
NSLog (#"numberOfWeekdays = %.2f", (secondsBeforeWeekend + secondsInInterveningWeeks + secondsAfterWeekend)/((float)dayInterval));
NSLog(#"endDateFromWeekdays = %#", [finalDate descriptionWithLocale:[NSLocale currentLocale]]);
return finalDate;
}
- (NSTimeInterval) calculateWeekdaysFrom:(NSDate*)_date1 and:(NSDate*)_date2 {
if (_date1 && _date2) {
NSTimeInterval secondsBeforeWeekend;
NSTimeInterval secondsAfterWeekend;
NSDate *dateOfFirstSaturdayMorning;
NSDate *dateOfLastSundayNight;
NSTimeInterval dayInterval = 24*60*60; // This isn't always true, e.g., if daylight savings intervenes. (But that happens on the weekend in most places.)
// see if they are in the same week
if (([_date1 ordinality] < [_date2 ordinality]) && [_date2 timeIntervalSinceDate:_date1] <= 5*dayInterval) {
return [_date2 timeIntervalSinceDate:_date1];
}
// time interval before a first weekend
if ([_date1 ordinality] == 1 || [_date1 ordinality] == 7) {
secondsBeforeWeekend = 0;
dateOfFirstSaturdayMorning = _date1; // This is just a convenience. It's not true. But, later, rounding takes place to deal with it.
}
else {
dateOfFirstSaturdayMorning = [_date1 theFollowingWeekend];
secondsBeforeWeekend = [dateOfFirstSaturdayMorning timeIntervalSinceDate:_date1];
}
int ordDate2 = [_date2 ordinality];
int ordFirstSaturday = [dateOfFirstSaturdayMorning ordinality];
// time interval after a last weekend
if ([_date2 ordinality] == 1 || [_date2 ordinality] == 7) {
secondsAfterWeekend = 0;
dateOfLastSundayNight = _date2; // Again, this is just a convenience. It's not true.
}
else {
dateOfLastSundayNight = [_date2 thePreviousWeekend];
secondsAfterWeekend = [_date2 timeIntervalSinceDate:dateOfLastSundayNight];
}
NSTimeInterval intervalBetweenWeekends = [dateOfLastSundayNight timeIntervalSinceDate:dateOfFirstSaturdayMorning];
int numberOfWeeks = (int) (intervalBetweenWeekends/(7*dayInterval));
int secondsInInterveningWeeks = (float) (5*dayInterval*numberOfWeeks);
NSLog(#"date 1 = %#", [_date1 descriptionWithLocale:[NSLocale currentLocale]]);
NSLog(#"date 2 = %#", [_date2 descriptionWithLocale:[NSLocale currentLocale]]);
NSLog(#"dateOfFirstSaturdayMorning = %#", [dateOfFirstSaturdayMorning descriptionWithLocale:[NSLocale currentLocale]]);
NSLog(#"dateOfLastSundayNight = %#",[dateOfLastSundayNight descriptionWithLocale:[NSLocale currentLocale]]);
NSLog (#"daysBeforeWeekend = %.2f", secondsBeforeWeekend/((float)dayInterval));
NSLog (#"daysBetweenWeekends = %.2f", secondsInInterveningWeeks/((float)(dayInterval)));
NSLog (#"daysAfterWeekend = %.2f", secondsAfterWeekend/((float)dayInterval));
NSLog (#"numberOfWeekdays = %.2f", (secondsBeforeWeekend + secondsInInterveningWeeks + secondsAfterWeekend)/((float)dayInterval));
return secondsBeforeWeekend + secondsInInterveningWeeks + secondsAfterWeekend;
}
else
return 0;
}
The files for category methods on NSDate are NSDate+help.h
#interface NSDate (help)
+ (NSDate *) LSExtendedDateWithNaturalLanguageString:(NSString *)dateString WithFormatter:(NSDateFormatter*)dateFormatter;
- (NSUInteger)ordinality;
- (NSDate*) theFollowingWeekend;
- (NSDate *) thePreviousWeekend;
- (NSDate *) dateByAddingDays:(NSInteger) numberOfDays;
- (NSDate *) dateByMovingToBeginningOfDayInTimeZone:(NSTimeZone*)tz;
- (NSDate *) dateByMovingToEndOfDayInTimeZone:(NSTimeZone*)tz;
#end
and NSDate+help.m
#import "NSDate+help.h"
#implementation NSDate (help)
// thrown in for testing
+ (NSDate *) LSExtendedDateWithNaturalLanguageString:(NSString *)dateString WithFormatter:(NSDateFormatter*)dateFormatter{
[dateFormatter setDateFormat:#"yyyy-MM-dd HHmm"];
[dateFormatter setLocale:[NSLocale currentLocale]];
//NSDate *formattedDate = [dateFormatter dateFromString:#"2008-12-3T22-11-30-123"];
return [dateFormatter dateFromString:dateString];
}
- (NSUInteger)ordinality {
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
return [calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSWeekCalendarUnit forDate:self];
}
- (NSDate*) theFollowingWeekend {
NSUInteger myOrdinality = [self ordinality];
NSDate *dateOfFollowingWeekend = [self dateByAddingDays:(7-myOrdinality)%7];
return [dateOfFollowingWeekend dateByMovingToBeginningOfDayInTimeZone:(NSTimeZone*)nil];
}
- (NSDate *) thePreviousWeekend {
NSUInteger myOrdinality = [self ordinality];
NSDate *dateOfPreviousWeekend = [self dateByAddingDays:(1-myOrdinality)];
return [dateOfPreviousWeekend dateByMovingToEndOfDayInTimeZone:(NSTimeZone*)nil];
}
- (NSDate *) dateByAddingDays:(NSInteger) numberOfDays {
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = numberOfDays;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
return [theCalendar dateByAddingComponents:dayComponent toDate:self options:0];
}
- (NSDate *) dateByMovingToBeginningOfDayInTimeZone:(NSTimeZone*)tz {
NSTimeZone *timezone;
if (tz)
timezone = tz;
else
timezone = [NSTimeZone systemTimeZone];
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
[parts setHour:0];
[parts setMinute:0];
[parts setSecond:0];
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:timezone];
return [calendar dateFromComponents:parts];
}
- (NSDate *)dateByMovingToEndOfDayInTimeZone:(NSTimeZone*)tz {
NSTimeZone *timezone;
if (tz)
timezone = tz;
else
timezone = [NSTimeZone systemTimeZone];
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
[parts setHour:23];
[parts setMinute:59];
[parts setSecond:59];
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:timezone];
return [calendar dateFromComponents:parts];
}
#end
The category method ordinality returns the number for the day of the week of the receiver. Sunday = 1, Saturday = 7. This is used to find out how many days there are before the end of the first week and how many days there are after the beginning the last week. (Calculations are actually carried out in seconds.)
The category methods theFollowingWeekend and thePreviousWeekend return the NSDate at midnight on the Saturday morning that follows the receiver date and the NSDate one second before midnight on the Sunday that follows the receiver date. These methods assume you have already validated that the receiver date is not on the weekend. I handled that in the main methods. Look for the checks of ordinality == 1 or 7.
dateByMovingToBeginningOfDayInTimeZone: and dateByMovingToEndOfDayInTimeZone: set the hours, minutes, and seconds of the receiver date to 00:00:00 and 23:59:59 respectively. This is for delimiting weekends, which run from midnight Saturday morning to midnight Sunday night in the timezone.
Hope this helps. This was an exercise for me to become more familiar with the time and date functionality.
I'll credit Keith Lazuka and his calendar component for iPhone for the germination of this code.
Here's a screen shot of a test program user interface that uses these functions:
Here is your example, run through the first method. The items of interest are highlighted.
. For this, I made the simple modification to accept fractional days (which i mentioned above, but did not include in the code shown above)
Using info from above I have made a simple method to work out weekdays between two dates. Could not find this anywhere so I thought I'd post.
- (NSInteger)endDate:(NSDate *)eDate minusStartDate:(NSDate *)sDate{
int weekDaysCount;
weekDaysCount = 0;
//A method that calculates how many weekdays between two dates
//firstcompare dates to make sure end date is not in the past
//using the NScomparisonresult and the NSDate compare: method
NSComparisonResult result = [sDate compare:eDate];
if (result == NSOrderedDescending) {
eDate = sDate;
//NSLog(#"invalid date so set to end date to start date");
}
//Work out the number of days btween the twodates passed in
//first set up a gregorian calander
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:sDate
toDate:eDate options:0];
//get the number of days
NSInteger days = [components day];
//now loop through the days and only count the weekdays
while (days > 0) {//while days are greater than 0
// NSLog(#"days = %i", days);
//get the weekday number of the start date
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:sDate];
// NSLog(#"sDate %#", sDate);
int weekday = [comps weekday];
// NSLog(#"Comps Weekday = %i", weekday);
//Test for a weekday - if its not a Saturday or Sunday
if ((weekday!=7) && (weekday !=1)){
//increase weekDays count
weekDaysCount ++;
// NSLog(#"weekDaysCount is %i", weekDaysCount);
// NSLog(#"-------------------------");
}
//decrement the days
days -=1;
//increase the date so the next day can be tested
sDate = [sDate dateByAddingTimeInterval:(60 * 60 * 24)];
}
return weekDaysCount;
}

How would I add only business days to an NSDate?

I have an issue related to calculating business days in Objective-C.
I need to add X business days to a given NSDate.
For example, if I have a date: Friday 22-Oct-2010, and I add 2 business days, I should get: Tuesday 26-Oct-2010.
Thanks in advance.
There are two parts to this:
Weekends
Holidays
I'm going to pull from two other posts to help me out.
For weekends, I'm going to need to know a given date's day of the week. For that, this post comes in handy:
How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?
For holidays, #vikingosegundo has a pretty great suggestion on this post:
List of all American holidays as NSDates
First, let's deal with the weekends;
I've wrapped up the suggestion in the post I cited above into this nice little helper function which tells us if a date is a weekday:
BOOL isWeekday(NSDate * date)
{
int day = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date] weekday];
const int kSunday = 1;
const int kSaturday = 7;
BOOL isWeekdayResult = day != kSunday && day != kSaturday;
return isWeekdayResult;
}
We'll need a way to increment a date by a given number of days:
NSDate * addDaysToDate(NSDate * date, int days)
{
NSDateComponents * components = [[NSDateComponents alloc] init];
[components setDay:days];
NSDate * result = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:0];
[components release];
return result;
}
We need a way to skip over weekends:
NSDate * ensureDateIsWeekday(NSDate * date)
{
while (!isWeekday(date))
{
// Add one day to the date:
date = addDaysToDate(date, 1);
}
return date;
}
And we need a way to add an arbitrary number of days to a date:
NSDate * addBusinessDaysToDate(NSDate * start, int daysToAdvance)
{
NSDate * end = start;
for (int i = 0; i < daysToAdvance; i++)
{
// If the current date is a weekend, advance:
end = ensureDateIsWeekday(end);
// And move the date forward by one day:
end = addDaysToDate(end, 1);
}
// Finally, make sure we didn't end on a weekend:
end = ensureDateIsWeekday(end);
return end;
}
Note; There is an obvious optimization I skipped - you could easily add more than one day at a time to the current date - but the point of my post is to show you how to do this yourself - and not necessarily to come up with the best possible solution.
Now lets tie that up and see what we have so far:
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSDate * start = [NSDate date];
int daysToAdvance = 10;
NSDate * end = addBusinessDaysToDate(start, daysToAdvance);
NSLog(#"Result: %#", [end descriptionWithCalendarFormat:#"%Y-%m-%d"
timeZone:nil
locale:nil]);
[pool drain];
return 0;
}
So, we've got weekends covered, now we need to pull in the holidays.
Pulling in some RSS feed, or data from another source is definitely beyond the scope of my post... so, let's just assume you have some dates you know are holidays, or, according to your work calendar, are days off.
Now, I'm going to do this with an NSArray... but, again, this leaves plenty of room for improvement - at minimum it should be sorted. Better yet, some sort of hash set for fast lookups of dates. But, this example should suffice to explain the concept. (Here we construct an array which indicates there are holidays two and three days from now)
NSMutableArray * holidays = [[NSMutableArray alloc] init];
[holidays addObject:addDaysToDate(start, 2)];
[holidays addObject:addDaysToDate(start, 3)];
And, the implementation for this will be very similar to the weekends. We'll make sure the day isn't a holiday. If it is, we'll advance to the next day. So, a collection of methods to help with that:
BOOL isHoliday(NSDate * date, NSArray * holidays)
{
BOOL isHolidayResult = NO;
const unsigned kUnits = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents * components = [[NSCalendar currentCalendar] components:kUnits fromDate:date];
for (int i = 0; i < [holidays count]; i++)
{
NSDate * holiday = [holidays objectAtIndex:i];
NSDateComponents * holidayDateComponents = [[NSCalendar currentCalendar] components:kUnits fromDate:holiday];
if ([components year] == [holidayDateComponents year]
&& [components month] == [holidayDateComponents month]
&& [components day] == [holidayDateComponents day])
{
isHolidayResult = YES;
break;
}
}
return isHolidayResult;
}
and:
NSDate * ensureDateIsntHoliday(NSDate * date, NSArray * holidays)
{
while (isHoliday(date, holidays))
{
// Add one day to the date:
date = addDaysToDate(date, 1);
}
return date;
}
And, finally, make some modifications to our addition function to take into account the holidays:
NSDate * addBusinessDaysToDate(NSDate * start, int daysToAdvance, NSArray * holidays)
{
NSDate * end = start;
for (int i = 0; i < daysToAdvance; i++)
{
// If the current date is a weekend, advance:
end = ensureDateIsWeekday(end);
// If the current date is a holiday, advance:
end = ensureDateIsntHoliday(end, holidays);
// And move the date forward by one day:
end = addDaysToDate(end, 1);
}
// Finally, make sure we didn't end on a weekend or a holiday:
end = ensureDateIsWeekday(end);
end = ensureDateIsntHoliday(end, holidays);
return end;
}
Go ahead and try it:
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSDate * start = [NSDate date];
int daysToAdvance = 10;
NSMutableArray * holidays = [[NSMutableArray alloc] init];
[holidays addObject:addDaysToDate(start, 2)];
[holidays addObject:addDaysToDate(start, 3)];
NSDate * end = addBusinessDaysToDate(start, daysToAdvance, holidays);
[holidays release];
NSLog(#"Result: %#", [end descriptionWithCalendarFormat:#"%Y-%m-%d"
timeZone:nil
locale:nil]);
[pool drain];
return 0;
}
If you want the whole project, here ya go: http://snipt.org/xolnl
There's nothing built into NSDate or NSCalendar that counts business days for you. Business days depend to some degree on the business in question. In the US, "business day" generally means weekdays that aren't holidays, but each company determines which holidays to observe and when. For example, some businesses move observance of minor holidays to the last week of the year so that employees can be off between Christmas and New Year's Day without taking vacation.
So, you'll need to decide exactly what you mean by business day. It should then be simple enough write a little method to calculate a future date by adding some number of business days. Then use a category to add a method like -dateByAddingBusinessDays: to NSDate.
this answer is late to the party but…. I thought i might improve on above answers to determine business days by working with NSDateComponents directly of your date in a nice loop.
#define CURRENTC [NSCalendar currentCalendar]
#define CURRENTD [NSDate date]
NSInteger theWeekday;
NSDateComponents* temporalComponents = [[NSDateComponents alloc] init];
[temporalComponents setCalendar:CURRENTC];
[temporalComponents setDay: 13];
[temporalComponents setMonth: 2];
[temporalComponents setYear: theYear];
// CURRENTC =the current calendar which determines things like how
// many days in week for local, also the critical “what is a weekend”
// you can also convert a date directly to components. but the critical thing is
// to get the CURRENTC in, either way.
case 3:{ // the case of finding business days
NSDateComponents* startComp = [temporalComponents copy]; // start date components
for (int i = 1; i <= offset; i++) //offset is the number of busi days you want.
{
do {
[temporalComponents setDay: [temporalComponents day] + 1];
NSDate* tempDate = [CURRENTC dateFromComponents:temporalComponents];
theWeekday = [[CURRENTC components:NSWeekdayCalendarUnit fromDate:tempDate] weekday];
} while ((theWeekday == 1) || (theWeekday == 7));
}
[self findHolidaysStart:startComp end:temporalComponents]; // much more involved routine.
[startComp release];
break;
}
// use startComp and temporalcomponents before releasing
// temporalComponents now contain an offset of the real number of days
// needed to offset for busi days. startComp is just your starting date….(in components)
// theWeekday is an integer between 1 for sunday, and 7 for saturday, (also determined
// by CURRENTC
turning this back into NSDate, and you are done. Holidays are much more involved.. but can actually be calculated if just using federal holidays and a few others. because they are always something like “3rd monday of January”
here is what the findHolidaysStart:startComp end: starts out like, you can imagine the rest.
// imported
[holidayArray addObject:[CURRENTC dateFromComponents:startComp]];
[holidayArray addObject:[CURRENTC dateFromComponents:endComp]];
// hardcoded
dateComponents = [[NSDateComponents alloc] init];
[dateComponents setCalendar:CURRENTC];
[dateComponents setDay: 1];
[dateComponents setMonth: 1];
[dateComponents setYear: theYear];
theWeekday = [[CURRENTC components:NSWeekdayCalendarUnit fromDate:[CURRENTC dateFromComponents:dateComponents]] weekday];
if (theWeekday == 1) [dateComponents setDay:2];
if (theWeekday == 7) {[dateComponents setDay:31]; [dateComponents setYear: theYear-1];}
[holidayArray addObject:[CURRENTC dateFromComponents:dateComponents]];
[dateComponents release];
I took #steve's answer and added a method to calculate the days of all the federal holidays in USA and put it all in a Category. I've tested it and it works nicely. Check it out.
#import "NSDate+BussinessDay.h"
#implementation NSDate (BussinessDay)
-(NSDate *)addBusinessDays:(int)daysToAdvance{
NSDate * end = self;
NSArray *holidays = [self getUSHolidyas];
for (int i = 0; i < daysToAdvance; i++)
{
// Move the date forward by one day:
end = [self addDays:1 toDate:end];
// If the current date is a weekday, advance:
end = [self ensureDateIsWeekday:end];
// If the current date is a holiday, advance:
end = [self ensureDateIsntHoliday:end forHolidays:holidays];
}
return end;
}
#pragma mark - Bussiness Days Calculations
-(BOOL)isWeekday:(NSDate *) date{
int day = (int)[[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date] weekday];
const int kSunday = 1;
const int kSaturday = 7;
BOOL isWeekdayResult = day != kSunday && day != kSaturday;
return isWeekdayResult;
}
-(NSDate *)addDays:(int)days toDate:(NSDate *)date{
NSDateComponents * components = [[NSDateComponents alloc] init];
[components setDay:days];
NSDate * result = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:0];
return result;
}
-(NSDate *)ensureDateIsWeekday:(NSDate *)date{
while (![self isWeekday:date])
{
// Add one day to the date:
date = [self addDays:1 toDate:date];
}
return date;
}
-(BOOL)isHoliday:(NSDate *)date forHolidays:(NSArray *)holidays{
BOOL isHolidayResult = NO;
const unsigned kUnits = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents * components = [[NSCalendar currentCalendar] components:kUnits fromDate:date];
for (int i = 0; i < [holidays count]; i++)
{
NSDate * holiday = [holidays objectAtIndex:i];
NSDateComponents * holidayDateComponents = [[NSCalendar currentCalendar] components:kUnits fromDate:holiday];
if ([components year] == [holidayDateComponents year]
&& [components month] == [holidayDateComponents month]
&& [components day] == [holidayDateComponents day])
{
isHolidayResult = YES;
break;
}
}
return isHolidayResult;
}
-(NSDate *)ensureDateIsntHoliday:(NSDate *)date forHolidays:(NSArray *)holidays{
while ([self isHoliday:date forHolidays:holidays])
{
// Add one day to the date:
date = [self addDays:1 toDate:date];
}
return date;
}
-(NSArray *)getUSHolidyas{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy";
NSString *year = [formatter stringFromDate:[NSDate date]];
NSString *nextYear = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:(60*60*24*365)]];
formatter.dateFormat = #"M/d/yyyy";
//Constant Holidays
NSDate *newYearsDay = [formatter dateFromString:[NSString stringWithFormat:#"1/1/%#",nextYear]]; //Use next year for the case where we are adding days near end of december.
NSDate *indDay = [formatter dateFromString:[NSString stringWithFormat:#"7/4/%#",year]];
NSDate *vetDay = [formatter dateFromString:[NSString stringWithFormat:#"11/11/%#",year]];
NSDate *xmasDay = [formatter dateFromString:[NSString stringWithFormat:#"12/25/%#",year]];
//Variable Holidays
NSInteger currentYearInt = [[[NSCalendar currentCalendar]
components:NSYearCalendarUnit fromDate:[NSDate date]] year];
NSDate *mlkDay = [self getTheNth:3 occurrenceOfDay:2 inMonth:1 forYear:currentYearInt];
NSDate *presDay = [self getTheNth:3 occurrenceOfDay:2 inMonth:2 forYear:currentYearInt];
NSDate *memDay = [self getTheNth:5 occurrenceOfDay:2 inMonth:5 forYear:currentYearInt]; // Let's see if there are 5 Mondays in May
NSInteger month = [[[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:memDay] month];
if (month > 5) { //Check that we are still in May
memDay = [self getTheNth:4 occurrenceOfDay:2 inMonth:5 forYear:currentYearInt];
}
NSDate *labDay = [self getTheNth:1 occurrenceOfDay:2 inMonth:9 forYear:currentYearInt];
NSDate *colDay = [self getTheNth:2 occurrenceOfDay:2 inMonth:10 forYear:currentYearInt];
NSDate *thanksDay = [self getTheNth:4 occurrenceOfDay:5 inMonth:11 forYear:currentYearInt];
return #[newYearsDay,mlkDay,presDay,memDay,indDay,labDay,colDay,vetDay,thanksDay,xmasDay];
}
-(NSDate *)getTheNth:(NSInteger)n occurrenceOfDay:(NSInteger)day inMonth:(NSInteger)month forYear:(NSInteger)year{
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.year = year;
dateComponents.month = month;
dateComponents.weekday = day; // sunday is 1, monday is 2, ...
dateComponents.weekdayOrdinal = n; // this means, the first of whatever weekday you specified
return [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
}
#end

Counting down the days - iPhone Count Down Timer

I’m trying to make a counter which shows the number of days until we leave on a trip to Europe. It’s only about 70 days (as of today) so I don’t believe that I should have to worry about astronomically large numbers or anything, but I really am stumped - I’ve attached the code that some friends have given me, which don’t work either. Trust me when I say I’ve tried everything I can think of - and before anyone bites my head off, which I have seen done on these forums, yes I did look very extensively at the Apple Documentation, however I’m not 100% sure where to start - I’ve tried NSTimer, NSDate and all their subclasses and methods, but there’s nothing that jumps out immediately.
In terms of what I think I should actually be doing, I think I need to somehow assign an integer value for the “day” today/ now/ the current day, which will change dynamically using the [NSDate date] and then the same for the date that we leave. The countdown is just updating when the method gets called again (I can do this using NSTimer if need be) and the value that is displayed on the countdown is the differnce between these two values.
I don’t especially want to have a flashing kind of thing that updates every second until we leave - personally I think that’s tacky, but if anyone knows how then I’d appreciate it for future reference.
I’ve also done an extensive search of google, and I may simply be using the wrong search terms, but I can’t find anything there either.
Any help is greatly appreciated.
Thank you very much.
Michaeljvdw
- (void)countDownMethod {
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:startDay];
[comps setMonth:startMonth];
[comps setYear:startYear];
[comps setHour:startHour];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
NSLog(#"%#",date);
[gregorian release];
[comps release];
NSTimeInterval diff = [date timeIntervalSinceNow];
int diffInt = diff;
NSString *days = [NSString stringWithFormat:#"%d",diffInt/86400];
day0.text = #"0";
day1.text = #"0";
day2.text = #"0";
NSLog(#"Days Length: %d",days.length);
if(days.length >= 1){
day2.text = [days substringFromIndex:days.length - 1];
if(days.length >= 2){
day1.text = [days substringWithRange:NSMakeRange(days.length - 2, 1)];
if(days.length >= 3){
day0.text = [days substringWithRange:NSMakeRange(days.length - 3, 1)];
}
}
}
NSString *hours = [NSString stringWithFormat:#"%d",(diffInt%86400)/3600];
hour0.text = #"0";
hour1.text = #"0";
NSLog(#"Hours Length: %d",hours.length);
if(hours.length >= 1){
hour1.text = [hours substringFromIndex:hours.length - 1];
if(hours.length >= 2){
hour0.text = [hours substringWithRange:NSMakeRange(hours.length - 2, 1)];
}
}
NSString *minutes = [NSString stringWithFormat:#"%d",((diffInt%86400)%3600)/60];
minute0.text = #"0";
minute1.text = #"0";
NSLog(#"Minutes Length: %d",minutes.length);
if(minutes.length >= 1){
minute1.text = [minutes substringFromIndex:minutes.length - 1];
if(minutes.length >= 2){
minute0.text = [minutes substringWithRange:NSMakeRange(minutes.length - 2, 1)];
}
}
}
If you know the time in seconds between 2 dates (your NSTimeInterval) then you can easily convert that into a string in the format days:hours:mins:secs as follows.
- (NSString*)secsToDaysHoursMinutesSecondsString:(NSTimeInterval)theSeconds {
div_t r1 = div(theSeconds, 60*60*24);
NSInteger theDays = r1.quot;
NSInteger secsLeftFromDays = r1.rem;
div_t r2 = div(secsLeftFromDays, 60*60);
NSInteger theHours = r2.quot;
NSInteger secsLeftFromHours = r2.rem;
div_t r3 = div(secsLeftFromHours, 60);
NSInteger theMins = r3.quot;
NSInteger theSecs = r3.rem;
NSString* days;
if (theDays < 10) { // make it 2 digits
days = [NSString stringWithFormat:#"0%i", theDays];
} else {
days = [NSString stringWithFormat:#"%i", theDays];
}
NSString* hours;
if (theHours < 10) { // make it 2 digits
hours = [NSString stringWithFormat:#"0%i", theHours];
} else {
hours = [NSString stringWithFormat:#"%i", theHours];
}
NSString* mins;
if (theMins < 10) { // make it 2 digits
mins = [NSString stringWithFormat:#"0%i", theMins];
} else {
mins = [NSString stringWithFormat:#"%i", theMins];
}
NSString* secs;
if (theSecs < 10) { // make it 2 digits
secs = [NSString stringWithFormat:#"0%i", theSecs];
} else {
secs = [NSString stringWithFormat:#"%i", theSecs];
}
return [NSString stringWithFormat:#"%#:%#:%#:%#", days, hours, mins,secs];
}
//Another simple way to get the numbers of days difference to a future day from today.
NSTimeInterval todaysDiff = [todayDate timeIntervalSinceNow];
NSTimeInterval futureDiff = [futureDate timeIntervalSinceNow];
NSTimeInterval dateDiff = futureDiff - todaysDiff;
div_t r1 = div(dateDiff, 60*60*24);
NSInteger theDays = r1.quot;
label.text = [NSString stringWithFormat:#"%i", theDays];

Number of days in given year using iPhone SDK?

I'm trying to get the number of days in a current year.
When I try the solution on Number of days in the current month using iPhone SDK?, and replace NSMonthCalendarUnit by NSYearCalendarUnit, I still get the number of days for that month.
Does anyone know how I should do this?
Thanks in advance for your help.
Here's a super accurate NSCalendar extension in Swift 2:
extension NSCalendar {
func daysInYear(date: NSDate = NSDate()) -> Int? {
let year = components([NSCalendarUnit.Year], fromDate: date).year
return daysInYear(year)
}
func daysInYear(year: Int) -> Int? {
guard let begin = lastDayOfYear(year - 1), end = lastDayOfYear(year) else { return nil }
return components([NSCalendarUnit.Day], fromDate: begin, toDate: end, options: []).day
}
func lastDayOfYear(year: Int) -> NSDate? {
let components = NSDateComponents()
components.year = year
guard let years = dateFromComponents(components) else { return nil }
components.month = rangeOfUnit(NSCalendarUnit.Month, inUnit: NSCalendarUnit.Year, forDate: years).length
guard let months = dateFromComponents(components) else { return nil }
components.day = rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: months).length
return dateFromComponents(components)
}
}
You can use it like this:
let calendar = NSCalendar.currentCalendar() // I'm using the Gregorian calendar
calendar.daysInYear() // 365 (since it's currently 2015)
calendar.daysInYear(2016) // 366 (leap year!)
This is super flexible since we don't assume anything about the length of the calendar:
let hebrew = NSCalendar(calendarIdentifier: NSCalendarIdentifierHebrew)
hebrew?.daysInYear(-7) // 354
hebrew?.daysInYear(-100) // 384
Enjoy.
If you're only going to use the Gregorian Calender, you can calculate it manually.
http://en.wikipedia.org/wiki/Leap_year#Algorithm
if year modulo 400 is 0 then leap
else if year modulo 100 is 0 then no_leap
else if year modulo 4 is 0 then leap
else no_leap
I finally came up with a solution that works. What I do is first calculate the number of months in the year and then for each month calculate the number of days for that month.
The code looks like this:
NSUInteger days = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:today];
NSUInteger months = [calendar rangeOfUnit:NSMonthCalendarUnit
inUnit:NSYearCalendarUnit
forDate:today].length;
for (int i = 1; i <= months; i++) {
components.month = i;
NSDate *month = [calendar dateFromComponents:components];
days += [calendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:month].length;
}
return days;
It is not as neat as I would have hoped for but it will work for any calendar such as the ordinary gregorian one or the islamic one.
Use the NSCalendar and NSDateComponent classes, like this:
long GetDaysInYear(int year) {
NSDateComponents* c = [[NSDateComponents alloc] init];
c.year = year;
NSCalendar* cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate* startDate = [cal dateFromComponents:c];
c.year += 1;
NSDate* endDate = [cal dateFromComponents:c];
return [cal components:NSDayCalendarUnit fromDate:startDate toDate:endDate options:0].day;
}
As example:
func daysInYear(year: Int) -> Int {
var calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var b = NSDate.dateWithNaturalLanguageString("01.01.\(year)", locale: NSLocale.currentLocale()) as! NSDate
var e = NSDate.dateWithNaturalLanguageString("12.31.\(year)", locale: NSLocale.currentLocale()) as! NSDate
return calendar!.components(NSCalendarUnit.CalendarUnitDay, fromDate: b, toDate: e, options: nil).day + 1
}
But default days return 355 and 354 this caused (may be) that counting begin from zero :)