user1032531
user1032531

Reputation: 26281

Comparing datetime to current time using PHP

Given $some_date equal to 2015-02-12 10:28:04, how can I determine whether it is not older than X hours of the current time using PHP (and not MySQL)?

Upvotes: 0

Views: 65

Answers (2)

Adam Joseph Looze
Adam Joseph Looze

Reputation: 1021

This will determine if your date is less than 2 hours from the current datetime

<?php
$date = new DateTime(); //set current datetime to variable
$date->setTimezone(new DateTimeZone('America/Detroit')); //set timezone if you like
$fdate = $date->format('Y-m-d H:i:s'); //change format to year - month - day, hour, minute, seconds

$some_date = strtotime('2015-02-13 18:30:04'); // this is your datetime.  use your time or change $some_date to your variable
$new_date = strtotime($fdate) - $some_date;
$minute_date = $new_date / 60; // convert to minutes
$hour_date = $minute_date / 60; // convert to hours

print $hour_date;

if($hour_date > 2){ // change the 2 to whatever you want it to be.
    print "more than two hours";
}else{
    print "less than two hours";
}
?>

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78984

strtotime and the DateTime class are our friends. Where $x is hours:

if(($time = strtotime($some_date)) > $time + ($x * 360)) {
    //do something its more than X hours
}

That likely won't work across daylight savings time boundaries, so maybe:

if(($time = strtotime($some_date)) > strtotime("+$x hours", $time)) {
    //do something its more than X hours
}

Upvotes: 2

Related Questions