7

I'm attempting to see if a time is within the last hour.

$unit_date = date($unit['last_accessed'], 'Y-m-d H:i:s');

$last_hour = date('Y-m-d H:i:s', strtotime('-1 hour')); 

if($unit_date >= $last_hour ){
    $connect = "<i class='fa fa-circle 2x' style='color:#2ECC71;'></i>";
} else {
    $connect = '';
}

As you can see I'm putting $unit['last_accessed'] into the correct format then comparing to an hour ago. If the time is within the last hour $connect is a font awesome circle (colored green), if it's not within the last hour it's empty, right now it's saying nothing is within the last hour which is false.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
user1890328
  • 1,222
  • 1
  • 13
  • 21

4 Answers4

13
if(time() - strtotime($unit['last_accessed']) < 3601){

or

if(time() - strtotime($unit['last_accessed']) > 3599){

time() and strtotime() both use the same time base in seconds

if $unit['last_accessed'] is already an integer time variable then do not use strtotime().

Misunderstood
  • 5,534
  • 1
  • 18
  • 25
3

DateTime solution

$firstDate = new \DateTime('2019-10-16 07:00:00');
$secondDate = new \DateTime('2019-10-17 07:00:00');

$diff = $firstDate->diff($secondDate);
$diffHours = $diff->h;

// diff in hours (don't worry about different years, it's taken into account)
$diffInHours = $diffHours + ($diff->days * 24);

// more than 1 hour diff
var_dump($diffInHours >= 1);

Origin similar answer: Calculate number of hours between 2 dates in PHP

Oleg Reym
  • 237
  • 4
  • 14
2

First of all, you're using date function in a wrong way. From PHP's manual:

date ( string $format [, int $timestamp = time() ] )

You must provide as first argument the $format string and the $timestamp as the second. You can check if the time is whitin the last hour without transform the Unix Timestamp to a another timestamp string.

$last_hour = time() - 60*60; //last hour timestamp
if($unit['last_accessed'] >= $last_hour){
       $connect = "<i class='fa fa-circle 2x' style='color:#2ECC71;'></i>";
}else{
       $connect = '';
}

As you can see, i didnt made any transformation to the timestamp, as i'm not using the timestring in anywhere. You should learn a little more about operations with unix timestamp's or about php time functions.

References: http://php.net/manual/en/function.date.php

BigBlast
  • 397
  • 1
  • 11
0

You've got an error in your code. In one place you call date like this:

date(format, time)

and in another place, like this:

date(time, format)

Check the PHP documentation for date and figure out which one is correct. Otherwise your code looks logically correct, if perhaps needlessly complex.

Brian A. Henning
  • 1,374
  • 9
  • 24