Page 1 of 1

php time question

Posted: Mon Feb 22, 2010 11:23 am
by jefffan24
Ok so I have a question about the best way to do something.

I'm creating a time management sort of thing with databases and users and what not. But what I need help with is what is most efficient way to get the difference between 2 times?

So like

4:45 AM and 1:20 PM

So I know that the difference between the two is 8 hours and 35 minutes. But what kind of algorithm can I use with php to get that?

I was thinking using unix time but I couldn't get it to work right so any ideas?

Re: php time question

Posted: Mon Feb 22, 2010 2:16 pm
by AbraCadaver
I don't know about best, but here is "a" way:

Code: Select all

$t1 = '4:45 AM';
$t2 = '1:20 PM';
 
$hours = floor(abs(strtotime($t1) - strtotime($t2)) / 3600);
$minutes = abs(strtotime($t1) - strtotime($t2)) % 3600 / 60;

Re: php time question

Posted: Mon Feb 22, 2010 3:08 pm
by jefffan24
So would I use like a date function to get the date?

Code: Select all

 
date("H:i A")
 
Or would I do that with unix time?

Re: php time question

Posted: Mon Feb 22, 2010 3:21 pm
by AbraCadaver
jefffan24 wrote:So would I use like a date function to get the date?

Code: Select all

 
date("H:i A")
 
Or would I do that with unix time?
I don't know what you're asking. You asked for the hour and minute difference between two times.

If you mean how to get $t1 and $t2 in the above example, then yes.

Re: php time question

Posted: Mon Feb 22, 2010 5:36 pm
by pickle
I don't know of any bullet-proof way to do this. ~AbraCadaver method would work for most cases, except when the two times are on either side of a time change (to or from Daylight Saving Time). Then you'd be off an hour either direction.

Re: php time question

Posted: Mon Feb 22, 2010 5:46 pm
by JakeJ
In the case of time zone differences, you'd have to pull the local time zone from the client computer and calculate against that. Probably base it all on GMT.

Re: php time question

Posted: Mon Feb 22, 2010 7:26 pm
by jefffan24
yeah I don't care about the actual time I just need to know the total time worked on a project (by the user pressing a start button setting a field and an end button setting another field). Then the code takes a difference of the 2 times to get the total time worked on the project.

Thanks for your replies I'll try some of the stuff posted here and see if I can get any of that to work.

Re: php time question

Posted: Mon Feb 22, 2010 7:45 pm
by Benjamin
Since the dates are stored in the database, depending on your implementation the best solution may be to use MySQL's built in TIMEDIFF() function.

http://dev.mysql.com/doc/refman/5.1/en/ ... n_timediff

Re: php time question

Posted: Tue Feb 23, 2010 8:47 am
by jefffan24
That is definitely interesting, I didn't know mysql could do that. I think that would the most efficient way to do this.