Show time left with PHP
|
Author: Mattias (mattias@problem.se) Categories: PHP |
||
|
|
||
|
The tutorial: Digg this, Post to del.icio.us, Let say you have a time or date in the future, and want to show your visitor the time left until that time. I want to show something like:
The function must be able to output any of these examples. The first example probably have some minutes and seconds aswell left, but they are not interesting so we only show days and hours. The same way if we are down ad hours, then we only show hours and minutes and so on...
The first part is "only" some math to seperate the days, hours, minutes and seconds (left). If it's one day and two seconds, we get back $days = 1, $hours = 0, $minutes = 0, $seconds = 2. The techniques used is called div and mod (/ and % operators). The give you back either how many whole times you can dived or the rest after a divition. Anyway, they are great for getting this information :-) don't bother if you don't care...
What I do after that is to check if we have any days and in that case write the number of days, check if we have minutes and if that is the case write them aswell. If we didn't have any days, we do a check to see if we have any hours... and so on and so on. the last way we can take is when we only have seconds left. Then we show only the seconds. (Of course we begin with checking that the date is in the future, otherwise we return "the time is already in the past!") And of course I will give you a small example for testing the function:
Hope you find lots of use for this function. I actually use it in some project we do as consults. Digg this, Post to del.icio.us, |
