Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating number of years between 2 dates in PHP

Tags:

date

php

I need to get the number of years from 2 dates provided. Here's my code:

function daysDifference($endDate, $beginDate) {    $date_parts1=explode("-", $beginDate);    $date_parts2=explode("-", $endDate);     $start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);    $end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);    $diff = $end_date - $start_date;    echo $diff;    $years = floor($diff / (365.25*60*60*24));    return $years; }  echo daysDifference('2011-03-12','2008-03-09'); 

The $diff gives a number output. When I return $years, am getting 0. What have I done wrong?

like image 622
Deepak Avatar asked Mar 22 '11 05:03

Deepak


People also ask

How can I get the number of days between two given dates in php?

The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.

How can I compare two time in php?

php $start = strtotime("12:00"); $end = // Run query to get datetime value from db $elapsed = $end - $start; echo date("H:i", $elapsed); ?>


Video Answer


1 Answers

$d1 = new DateTime('2011-03-12'); $d2 = new DateTime('2008-03-09');  $diff = $d2->diff($d1);  echo $diff->y; 
like image 130
Matthew Avatar answered Oct 01 '22 18:10

Matthew