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 Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable using a current_date function 2

Status
Not open for further replies.

sinbadly

Technical User
Mar 16, 2006
126
GB
I want to say so many days left till The Event.

The distance to the time is currentdate – 2006-03-31.

Is there a way to declare a variable - $to_event, for instance - which states this and I can use it with an echo, please?

I have searched php functions, but I can’t find one for current date. (I accept I must be blind.)
 
the code below will do what you want. it ignores whether the event is in the past or the future. you can change this by getting rid of the "abs" in the second line of get_time_diff.


Code:
$to_event = get_time_diff("2006-03-31", "format");
echo "<pre>";
print_r "$to_event";
echo "</pre>";

function get_time_diff($date, $format="seconds") {
  $datestamp = strtotime($date);
  $seconds = abs(strtotime("now") - $datestamp);
  if($format === "seconds"):
    return array("seconds"=>$seconds);  
  else:
   return time_format($seconds);
  endif;
}
function time_format($seconds) {
  $seconds = (float) $seconds;
  $secs = round((($seconds/60)-floor($seconds/60)) * 60,1);
  $mins = floor((($seconds/3600)-floor($seconds/(3600))) *60) ;
  $hrs = floor((($seconds/(3600*24))-floor($seconds/(3600*24))) *24) ;
  $days = floor($seconds / (3600*24));
  $days = ($days<0) ? 0 : $days;
  return  array("days"=>$days, "hours"=>$hours, "mins"=>$minutes, "seconds"=>$seconds);
}
 
See PHP Manual, Part IV, Function Reference, Date and Time functions. It's time() function. See also mktime() function (convert year-month-day in int seconds) in the same part then subtract two int values (in seconds)...

 
Many thanks, again, Justin. I thought it would be a simple $timetogo = this-date - event_date. No idea I was putting you to such trouble. But thanks very much. It will get a lot of use.

Thanks, ArkM for the reference. All noted.
 
it is as simple as you say. the format code was in case you wanted the output as days hours minutes and seconds (as people often do).

the actual time difference (in seconds) can be achieved by just the following (where $date is something like "2006-03-21"

Code:
$seconds = abs(strtotime("now") - strtotime($date));
 
Hi Justin

When IE looks at the print_r line, it finds an unexpected "'". When mozilla looks at it, it reckons it has found an unexpected T_Constant_Encapsed_etc

Does that ring any bells, please?

paul
 
yes. the variable should be in brackets and not in quotes.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top