Jump to content

Calculating Time Difference


mojomystery

Recommended Posts

I've seen similar solutions offered as to what I'm looking for but this is a slight twist that I need help with.

 

In a mySQL table, I have a "time" (not timestamp) value. Example : 18:00:00 Unfortunately I don't have have date values to show which date this time was from. Here's what I want to do.

 

Here's some sample data to work with:

 

Current Time - 14:00

Time value # 1 from a mySQL query - 18:00:00

 

Time value # 2 from a mySQL query - 13:00:00

 

 

In PHP, I want to assume that, any time in the future is actually from the previous day.

I then want to calculate the difference in time between the current time and any time value I pull from a query.and store that in a variable.

For example, using time value #1 from above, the difference would be 20:00:00 (since it was 20 hours ago). Using time value #2, the difference would be 1:00:00 (only 1 hour).

 

It sounds simple but I might be over analyzing my problem to figure this out.

 

Thanks for any help offered :)

 

- dan -

Link to comment
https://forums.phpfreaks.com/topic/273563-calculating-time-difference/
Share on other sites

You could do it in the query (assuming the column is defined as a TIME datatype):

 

SELECT IF (TIME(NOW()) < ColumnName, 
   TIMEDIFF('24:00:00', TIMEDIFF(ColumnName, TIME(NOW()))), 
   TIMEDIFF(TIME(NOW()), ColumnName)) AS `TimeDiff`
FROM TableName

 

There are probably half-a-dozen ways to do it in PHP, but I think doing it in the query is more efficient.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.