yehudahs
yehudahs

Reputation: 2668

Check how many days were passed since the last update in PHP

I am trying to check how many days were passed since the user last entered the system. I get the last time he\she entered from mysql table column (datetime). so I wrote :

$user_last_visit = $user_info['last_updated']; // 2013-08-08 00:00:00

$user_last_visit_str = strtotime($user_last_visit); // 1375912800
$today = strtotime(date('j-m-y')); // 1250114400

$diff = $today - $user_last_visit_str;

Some reason $diff = $today - $user_last_visit_str; is negative instead of getting a positive value with 24*60*60*1000 (one day = 24*60*60*1000 ms).

Any ideas?

Upvotes: 0

Views: 1532

Answers (5)

sgbj
sgbj

Reputation: 2274

A simple solution using diff:

echo date_create()->diff(date_create($user_last_visit))->days;

If all else fails, just do:

$diff = floor((time() - $user_last_visit_str) / (60 * 60 * 24));

Upvotes: 2

rink.attendant.6
rink.attendant.6

Reputation: 46287

Try using a DateTime object if your version of PHP supports it:

$user_last_visit = DateTime::createFromFormat('Y-m-d H:i:s', $user_info['last_updated']);
$today = new DateTime();
$diff = $today->diff( $user_last_visit, true );

echo $diff->days;

$diff will be a DateInterval object.

Upvotes: 1

Debashis
Debashis

Reputation: 596

Try this:

$user_last_visit = $user_info['last_updated']; // considering the value of user last visit is 2013-08-08 00:00:00 which indicates year, month, day, hour, minute, second respectiveliy
$user_last_visit_str = strtotime($user_last_visit);
$today = time();

$diff = $today - $user_last_visit_str;
$no_of_days = ($diff / (60*60*24));

Upvotes: 1

sudhakar
sudhakar

Reputation: 572

you can use below code to get date diff, here i given static last date which is 15th july 2013, and taking different from current date.

    $last_date = date('y-m-d', strtotime('15th july 2013'));//here give your date as i mentioned below
    //$last_date = date('y-m-d', strtotime($your_old_date_val));
$current_date = date('y-m-d');//

echo $date_diff = strtotime($current_date) -  strtotime($last_date) ;
echo $val = 60*60*24;
$days_diff = $date_diff / $val;

echo $days_diff;

Upvotes: 1

Peter Carrero
Peter Carrero

Reputation: 1606

try reversing the $today assignment, like so:

$today = strtotime(date('y-m-j'));

that worked for me.

Upvotes: 0

Related Questions