proR
proR

Reputation: 39

PHP - Calculate the difference between two dates

I want to calculate the number of years between two dates. One of them is retrieved from the database while the other is taken from user input in date format.

I used this code to get the date from the user:

$today   = $_POST['to-day'];
$tomonth = $_POST['to-month'];
$toyaer  = $_POST['to-year'];
$dateto  = date("$toyaer-$tomonth-$today");

And here is how I calculated it with the one retrieved from the database,

$start      = $leaveresult['date']; // i took from database 
$end        = strtotime($dateto);   
$difference = abs($end - $start);
$years      = floor($difference / (60*60*24*365));

The problem is that the result I get is always 0.

I tried different methods but all of them resulted with 0 and one of them resulted with a huge number.

Upvotes: 1

Views: 1925

Answers (3)

sesser
sesser

Reputation: 1165

The DateTime class simplifies all this by giving you a diff method. This will return a DateInterval object which you can get the values you're looking for.

Assuming $_POST looks like this:

$_POST = array(
    'to-year' => 2010,
    'to-month' => 8,
    'to-day' => 22
);

And $leaveresult['date'] looks like this:

$leaveresult = array(
    'date' => date('Y-m-d H:i:s', strtotime('-5 years')));

You can do something like this...

$input_date = new DateTime(sprintf("%d-%d-%d", $_POST['to-year'], $_POST['to-month'], $_POST['to-day']));
$database_date = new DateTime($leaveresult['date']);

$diff = $database_date->diff($input_date);

echo $diff->format('%r%y years') . PHP_EOL;
echo $diff->format('%r%m months') . PHP_EOL;
echo $diff->format('%r%d days') . PHP_EOL;

$years = $diff->y;

Which will yield

3 years
1 months
5 days  

And $years will equal 3

Upvotes: 2

Sabeen Malik
Sabeen Malik

Reputation: 10880

This is untested but I think something like this will work:

$today = $_POST['to-day'];
$tomonth = $_POST['to-month'];
$toyear = $_POST['to-year'];
$dateto = "$toyear-$tomonth-$today";

$start = $leaveresult['date'];// i took from database 
$end = strtotime($dateto);   
$difference = abs($end - $start);
$years = floor($difference / (60*60*24*365));

I am assuming $leaveresult['date'] is unix timestamp

Also please note that I fixed the post variable names.

If the start date is not in unix timestamp then use

$start = strtotime($leaveresult['date']);// i took from database 

Upvotes: 3

irr.licht
irr.licht

Reputation: 13

you need in both cases a timestamp - the one you formatted ( as date object ) and the one you get from the database... so I think you'r approach wasn't wrong, if your getting timestamps in both cases... but finally you've tried to round the number with floor... and of course this will result in 0, if it's less than a year. test it without rounding first, and test your timestamps, maybe something is wrong there, too?

Upvotes: 1

Related Questions