1

My friend and I are working on a fairly basic uptime script for an IRC Bot.

Here's our code:

function Uptime()
{
    global $uptimeStart;
    $currentTime = time();
    $uptime = $currentTime - $uptimeStart;
    $this->sendIRC("PRIVMSG {$this->ircChannel} :Uptime: ".date("z",$uptime)." Day(s) - ".date("H:i:s",$uptime));
}

$uptimeStart is set immediately when the script runs, as time();

for some reason when I execute this function, it starts at 364 days and 19 hours. I can't figure out why.

halfer
  • 19,824
  • 17
  • 99
  • 186
Rob
  • 7,980
  • 30
  • 75
  • 115
  • 1. Why don't you pass variable as function argument 2. `var_dump($currentTime, $uptimeStart)` 3. To count differnce use simple math, not `date()` – zerkms Jan 23 '11 at 15:07

4 Answers4

4

Your $uptime is not a timestamp as should be used in date(), but a difference in time. You have an amount of seconds there, not a timestamp (that corresponds with an actual date.

just use something like this to cacluate (quick one, put some extra brain in for things like 1 day, 2 hours etc) ;)

 $minutes = $uptime / 60;
 $hours   = $minuts/60 ;
 $days    = $hours / 24

etc

Nanne
  • 64,065
  • 16
  • 119
  • 163
2

If you have 5.3 or above, use the DateTime and DateInterval classes:

$uptimeStart = new DateTime(); //at the beginning of your script

function Uptime() {
  global $uptimeStart;
  $end = new DateTime();

  $diff = $uptimeStart->diff($end);

  return $diff->format("%a days %H:%i:%s");
}
Maerlyn
  • 33,687
  • 18
  • 94
  • 85
1

You won't get anything meaninful by calling date() on that time difference. You should take that time difference and progressively divide with years, months, days, hours, all measured in seconds. That way you'll get what the time difference in those terms.

$daySeconds = 86400 ;
$monthSeconds = 86400 * 30 ;
$yearSeconds = 86400 * 365 ;

$years = $uptime / $yearSeconds ;
$yearsRemaining = $uptime % $yearSeconds ;

$months = $yearsRemaining / $monthSeconds ;
$monthsRemaining = $yearsRemaining % $monthSeconds ;

$days = $monthsRemaining / $daySeconds ;

.. etc to get hours and minutes.

Fanis Hatzidakis
  • 5,282
  • 1
  • 33
  • 36
0

date() function with second argument set to 0 will actually return you (zero-date + (your time zone)), where "zero-date" is "00:00:00 1970-01-01". Looks like your timezone is UTC-5, so you get (365 days 24 hours) - (5 hours) = (364 days 19 hours)

Also, date() function is not the best way to show the difference between two dates. See other answers - there are are already posted good ways to calculate difference between years

Kel
  • 7,680
  • 3
  • 29
  • 39