Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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");
}

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top