jameslittle230
jameslittle230

Reputation: 3108

How do I calculate elapsed time within certain ranges?

I have a Laravel application that essentially provides a backend for a game. This game spans multiple days, but only certain hours within each day. Ideally, I'd like to have a "time elapsed" display, but I want that display to only count the time in-game, rather than the time since the start.

For example: this game will be functional Monday through Friday, 8AM to 3PM. Imagining the game starts on a Monday at 8AM, if it were Thursday at 10AM I would want the time elapsed display to show 23:00:00.

How should I store these date time ranges? There isn't an upper limit for the number of days, so I can't store them in a multidimensional array. How would you approach this?

Upvotes: 0

Views: 141

Answers (1)

Halcyon
Halcyon

Reputation: 57723

function get_hours_elapsed($day, $hour) {
    $time_start = 8; // 8am;
    $time_end = 15; // 3pm
    $day_start = 1; // Mon
    $day_end = 5; // Fri

    $days_elapsed = max(min($day, $day_end) - $day_start, 0);
    $hours_elapsed = $days_elapsed * ($time_end - $time_start);

    $hours_elapsed += max(min($hour, $time_end) - $time_start, 0);

    return $hours_elapsed;
}

var_dump(get_hours_elapsed(
    date("N"), // 0 - 6, 0 being Sunday
    date("G") // 0 - 23
)); // actual time
var_dump(get_hours_elapsed(4, 10)); // 10 am on a Thursday

Since it's Wednesday 5pm for me it prints:

int(21);
int(23);

If the time runs for multiple weeks just add num_weeks * total_hours_in_week hours.

If the timer doesn't start on Monday 8am, substract the number of hours. So if it starts at 10am on a Thursday, substract 23.

Upvotes: 1

Related Questions