Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Time left until a specified date

Status
Not open for further replies.

paulbradley

Programmer
Oct 9, 2002
158
GB
Using MySQL and php I need to be able to return the number of days, hours, mins and secs from the current date and time to a stored date and time in a table. Is there an easy way of doing this?

Many thanks in advance.
 
Code:
select current_timestamp
     , stored_datetime
     , concat(
        case 
         when 
          unix_timestamp(stored_datetime)
         -unix_timestamp(current_timestamp) 
             > 86400
         then concat(''
                   , floor(
         (unix_timestamp(stored_datetime)
         -unix_timestamp(current_timestamp))
                 / 86400 )  
                   , ' days, ' )
         else '' end 
     , sec_to_time(    
         mod(
          unix_timestamp(stored_datetime)
         -unix_timestamp(current_timestamp)
                ,86400) 
                  )
            ) as diff
  from yourtable

rudy | r937.com | Ask the Expert | Premium SQL Articles
SQL for Database-Driven Web Sites (next course starts March 6 2005)
 
Unfortunately, that solution only works for date/times in the future, not in the past. You could use instead something like:
[tt]
SELECT
datetimefield,
secsdiff,
FLOOR(ABS(secsdiff)/86400) daysdiff,
SEC_TO_TIME(ABS(secsdiff)%86400) timediff
FROM
(
SELECT
datetimefield,
UNIX_TIMESTAMP(datetimefield)-UNIX_TIMESTAMP(NOW())
secsdiff
FROM tablename
)
s
[/tt]
where the sign of the secsdiff field indicates past/future. This works with MySQL 4.1 onwards.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top