ChrisM
ChrisM

Reputation: 329

Calculating the day time and night time between two dates

I am trying to calculate, in seconds, the amount of day time and night time between two dates, given that "night time" is defined as 8:00PM through 7:59 AM, and "day time" as 8:00AM through 7:59PM. The past date that I will be comparing to the current timestamp will always be less than 24 hours than the time now.

How would I do this?

Upvotes: 1

Views: 2218

Answers (2)

lnafziger
lnafziger

Reputation: 25740

This quickly becomes complicated when you start dealing with daylight savings time and such, so you really need to work with your current calendar and use the calendar/date functions for calculating time differences.

For instance, if the clock moves forward 1 hour at 3:00 AM, you should have 11 hours of "night" (instead of 12) by your definition on the day of the time change.

I have not thoroughly tested this code, but it should be pretty close:

// 8:00:00 AM in seconds
static const NSTimeInterval daytimeStart = 28800;
// 8:00:00 PM in seconds
static const NSTimeInterval daytimeStop  = 72000;

// Convert date to a "time" which is the number of seconds since midnight, NOT considering time changes
- (NSTimeInterval)getTimeForDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];

    NSDateComponents *dateComps = [cal components:NSHourCalendarUnit | 
                                                    NSMinuteCalendarUnit | 
                                                    NSSecondCalendarUnit
                                         fromDate:date];
    NSTimeInterval time = dateComps.hour * 3600 + dateComps.minute * 60 + dateComps.second;
    return time;
}

// Set the time to the specified hour and minutes/seconds to 0
- (NSDate *)dateBySettingTimeToBeginningOfHour:(NSUInteger)hour ofDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];

    NSDateComponents *dateComps = [cal components:NSYearCalendarUnit |
                                   NSMonthCalendarUnit |
                                   NSDayCalendarUnit |
                                   NSHourCalendarUnit | 
                                   NSMinuteCalendarUnit | 
                                   NSSecondCalendarUnit
                                         fromDate:date];
    [dateComps setHour:hour];
    [dateComps setMinute:0];
    [dateComps setSecond:0];
    NSDate *newDate = [cal dateFromComponents:dateComps];
    return newDate;
}

// Add one day to the current date
- (NSDate *)dateByAddingOneDayToDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];

    NSDateComponents *dateComps = [cal components:NSYearCalendarUnit |
                                   NSMonthCalendarUnit |
                                   NSDayCalendarUnit |
                                   NSHourCalendarUnit | 
                                   NSMinuteCalendarUnit | 
                                   NSSecondCalendarUnit
                                         fromDate:date];
    [dateComps setDay:[dateComps day] + 1];
    NSDate *newDate = [cal dateFromComponents:dateComps];
    return newDate;
}

// Check to see if it is daytime
- (BOOL)isDayForDate:(NSDate *)date {
    NSTimeInterval time = [self getTimeForDate:date];
    if (time >= daytimeStart) {
        if (time < daytimeStop) {
            return YES;
        }
    }

    // Default
    return NO;
}

// Check to see if it is night
- (BOOL)isNightForDate:(NSDate *)date {
    return ![self isDayForDate:date];
}

// When do we transition from day to night or night to day next?
- (NSDate *)dateForNextTransitionForDate:(NSDate *)date {
    NSTimeInterval time = [self getTimeForDate:date];
    if (time < daytimeStart) {
        return [self dateBySettingTimeToBeginningOfHour:8 ofDate:date];
    }

    if (time < daytimeStop) {
        return [self dateBySettingTimeToBeginningOfHour:20 ofDate:date];
    }

    // Tomorrow morning
    NSDate *newDate = [self dateByAddingOneDayToDate:date];
    newDate = [self dateBySettingTimeToBeginningOfHour:8 ofDate:newDate];
    return newDate;
}

- (NSTimeInterval)nightTimeFromDate:(NSDate *)startingDate toDate:(NSDate *)laterDate {
    if ([startingDate compare:laterDate] != NSOrderedAscending) {
        return 0;
    }

    NSTimeInterval nightTime    = 0;
    NSDate *now                 = laterDate;
    NSDate *transitionDate      = startingDate;
    NSDate *loopDate            = startingDate;
    BOOL isNight                = [self isNightForDate:startingDate];

    do {
        transitionDate = [self dateForNextTransitionForDate:transitionDate];
        if ([transitionDate compare:now] == NSOrderedDescending) {
            transitionDate = now;
        }

        if (isNight) {
            nightTime = nightTime + [transitionDate timeIntervalSinceDate:loopDate];
        }

        loopDate = transitionDate;
        isNight = !isNight;
    } while ([transitionDate compare:now] != NSOrderedSame);

    return nightTime;
}

- (NSTimeInterval)dayTimeFromDate:(NSDate *)startingDate toDate:(NSDate *)laterDate {
    if ([startingDate compare:laterDate] != NSOrderedAscending) {
        return 0;
    }

    NSTimeInterval diff = [laterDate timeIntervalSinceDate:startingDate];
    diff = diff - [self nightTimeFromDate:startingDate toDate:laterDate];
    return diff;
}

// Example usage:
NSDate *now  = [NSDate date];
NSDate *date = [NSDate dateWithTimeInterval:-82800 sinceDate:now];

NSLog(@"%f", [self nightTimeFromDate:date toDate:now]);
NSLog(@"%f", [self dayTimeFromDate:date toDate:now]);

// Results are 43200.000000 and 39600.000000 right now in the middle of the day.

Upvotes: 4

Matisse VerDuyn
Matisse VerDuyn

Reputation: 1138

Daytime hours = ((# of days between today and last day) * 12) + (# of daytime hours today) + (# of daytime hours on last day)

Nighttime hours = ((# of days between today and last day) * 12) + (# of nighttime hours today) + (# of nighttime hours on last day)

EDIT

int dthours = 0, nthours = 0;

dthours += ternary with a calculation of 24 - starthour logic for daytime
nthours += ternary with a calculation of 24 - starthour logic for nighttime
dthours += ternary with a calculation of endhour logic for daytime
nthours += ternary with a calculation of endhour logic for nighttime

logic for tomorrow's nighttime hours looks something like:

nthours += (endhour - 4 > 0) ? ((endhour - 16 > 0) ? endhour - 12 : 4) : endhour;

Upvotes: 1

Related Questions