Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Comparing date, checking if within last hour

Tags:

date

php

datetime

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.

like image 761
user1890328 Avatar asked Mar 12 '15 14:03

user1890328


2 Answers

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().

like image 200
Misunderstood Avatar answered Sep 27 '22 20:09

Misunderstood


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

like image 43
Oleg Reym Avatar answered Sep 27 '22 22:09

Oleg Reym