Paul
Paul

Reputation: 11756

Easier way for PHP date calculations?

I'm trying to determine when a user has last logged on. My current method works but is there an easier way of determining this so that I could determine last X hours etc?

This is what I currently use:

$last_login_di = getdate($last_login);

$now = time();
$now_di = getdate($now);
$today = mktime(0,0,0,$now_di['mon'],$now_di['mday'], $now_di['year']);
if ($last_login > $today) {
    return 'Online Today';
}

$yesterday = $now-86400;
$yesterday_di = getdate($yesterday);
$yesterday = mktime(0,0,0,$yesterday_di['mon'],$yesterday_di['mday'], $yesterday_di['year']);
if ($last_login > $yesterday) {
    return 'Online Yesterday';
}

if (($now - $last_login < 604800) ) {
    return 'Online This Week';
}

....

Upvotes: 0

Views: 96

Answers (5)

Daniel Ribeiro
Daniel Ribeiro

Reputation: 10234

You should heavily use the date objects built-in with PHP.

$now = new DateTime();
$yesterday = new DateTime('yesterday');
$lastWeek = new DateTime('last week');

Now you are able to to any comparison logic you want, using the basic comparison operators:

if ($last_login > $now) {
    ...
} else if ($last_login > $yesterday) {
    ...
} else if ($last_login > $lastWeek) {
    ...
} else {
    ...
}

If you choose not to use the objects, try to avoid the time() function. That makes unit testing impossible. Tests should never depend on environment.

Use $_SERVER['REQUEST_TIME'] instead so you can mock it later.

Upvotes: 0

complex857
complex857

Reputation: 20753

Try strtotime() (see relative formats it accepts) or better yet, the DateTime, DateInterval classes.

For example, the $yesterday variable creation is prone errors near datetime savings. strtotime() handles this properly with:

$yesterday = strtotime('-1 day');

While the $last_login check can be written like:

if (strtotime('-1 week') < $last_login) {
    // ...
}

If you need to support different timezones you probably better of with the DateTime objects though.

Upvotes: 3

I think your code's fine. But the $yesterday var is wrong. It should be:

$yesterday = $today - 86400;

In your code $yesterday means $a_day_ago.

The same for the last week.

Upvotes: 0

Richard
Richard

Reputation: 4415

How do you get the date? Using MySQL? Use UNIX_TIMESTAMP for dates, eg SELECT UNIX_TIMESTAMP(last_login) AS last_login_timestamp FROM ... Then you can better calculate in PHP (using date_diff)

Upvotes: 1

Christian Kiewiet
Christian Kiewiet

Reputation: 880

Have a look at the DateTime and related classes DateTime Book on php.net. The DateInterval class may be of particular use to you.

Upvotes: 1

Related Questions