Patrik Krehák
Patrik Krehák

Reputation: 2683

PHP difference between dates

I am developing game and I need to show to player, how much day he is under protection. This is what I have for now:

if(user::loged()){
  $protect = (60*60*24*8) - (time() - user::info['reg_date']);
  $left = date("n",$protect);
  if($left > 0) echo "You are protected for $left days!";
}

For first (test) user reg_date is 1394883070 (15.3.2014 11:31). So it should print

You are protected for 7 days!

But I get that

You are protected for 1 days!

Any ideas?

Upvotes: 1

Views: 69

Answers (3)

makallio85
makallio85

Reputation: 1356

<?php
   $protect = (60*60*24*8) - (time() - user::info['reg_date']);
   $left = ltrim(date("d",$protect), 0);
   if($left > 0) echo "You are protected for $left days!";
   // Prints "You are protected for 7 days!"
?>

Upvotes: 0

Lajos Veres
Lajos Veres

Reputation: 13725

You should do something like this:

$days_since_registration = (time() - user::info['reg_date'])/(24*3600)

date() is useful for only unix timestamps. The difference of timestamps is a time interval in seconds, if you use it as a timestamp you are using dates in 1970 or something similar happens.

Upvotes: 2

Barry Carlyon
Barry Carlyon

Reputation: 1058

You have set $left to the number of months.

n is Numeric representation of a month, without leading zeros - http://php.net/date

I would do

if(user::loged()){
  $protect = 691200 - (time() - user::info['reg_date']);
  $left = ceil($protect / 86400);
  if($left > 0) echo "You are protected for $left days!";
}

Upvotes: 1

Related Questions