Subtracting between timestamps

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
AlbinoJellyfish
Forum Commoner
Posts: 76
Joined: Sun Apr 04, 2004 7:39 pm

Subtracting between timestamps

Post by AlbinoJellyfish »

I have a script where I need to figure out the time between two timestamps in a database and I don't know how I should go about doing this.
So lets say:
$startTime = "2004-05-19 16:03:40" and $endTime = "2004-05-19 16:03:44"
How would I subtract startTime from endTime to get the total number of seconds in between.
It wont always be 4 seconds, it might be a few minutes too.
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

MySQL has a ton of powerful date and time functions

http://dev.mysql.com/doc/mysql/en/date- ... tions.html
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

I take it you've stored your dates as MySQL timestamps? You're in luck! MySQL has the ability to convert it's timestamps into UNIX timestamps. You can then subtract the one from the other and voila!

Code: Select all

SELECT
  UNIX_TIMESTAMP(startTime) - UNIX_TIMESTAMP(endTime) as 'difference'
FROM
  someTable
`difference` is now the difference in seconds.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply