muttley91
muttley91

Reputation: 12674

Total Duration using DateTime

I've asked a few questions today based on some problems I've been having involving average and total duration of time between several DateTime values. In counting this duration, it was previously recommended that I use a DateTime object define as follows to store the total duration:

$totalTime = new DateTime("@0");

The question I have is - is it actually best to count total duration this way? Will it work to count the total duration of several events?

EDIT: The times being added are durations calculated by date_diff(), so they are DateInterval objects (which can easily be added to DateTime objects).

Upvotes: 1

Views: 177

Answers (1)

muttley91
muttley91

Reputation: 12674

From what I've been able to gather so far, there seem to be 2 "better" methods of doing this sort of thing.

  1. While still using a DateTime object, add all of the times up as seconds. This allows for simple integer addition/subtraction/whatever for counting the data, avoiding potential DateTime bugs/weird behaviour. In the end, just convert your seconds into a DateTime format for output.

  2. If pulling from a database (as I am), simply use SQL's available features for SUM, TIME_DIFF, and so on, to calculate directly from the database. From there, you pull it into a DateTime object in PHP and, without having to modify that object at all, output your results. This solved my own problem of going over 23 hours (which would go back to midnight if adding to a DateTime object in PHP).

I'm definitely open to other suggestions, however.

Upvotes: 1

Related Questions