I want calculate the difference between two dates in Javascript. Result should be X years, Y months, Z days
I run below code in PHP but result is different. Which is problem in here?
PHP CODE 1
// Declare and define two dates
$date1 = strtotime("2010-04-01");
$date2 = strtotime("2019-06-30");
// Formulate the Difference between two dates
$diff = abs($date2 - $date1);
// To get the year divide the resultant date into
// total seconds in a year (365*60*60*24)
$years = floor($diff / (365*60*60*24));
// To get the month, subtract it with years and
// divide the resultant date into
// total seconds in a month (30*60*60*24)
$months = floor(($diff - $years * 365*60*60*24)
/ (30*60*60*24));
// To get the day, subtract it with years and
// months and divide the resultant date into
// total seconds in a days (60*60*24)
$days = floor(($diff - $years * 365*60*60*24 -
$months*30*60*60*24)/ (60*60*24));
// To get the hour, subtract it with years,
// months & seconds and divide the resultant
// date into total seconds in a hours (60*60)
$hours = floor(($diff - $years * 365*60*60*24
- $months*30*60*60*24 - $days*60*60*24)
/ (60*60));
// To get the minutes, subtract it with years,
// months, seconds and hours and divide the
// resultant date into total seconds i.e. 60
$minutes = floor(($diff - $years * 365*60*60*24
- $months*30*60*60*24 - $days*60*60*24
- $hours*60*60)/ 60);
// To get the minutes, subtract it with years,
// months, seconds, hours and minutes
$seconds = floor(($diff - $years * 365*60*60*24
- $months*30*60*60*24 - $days*60*60*24
- $hours*60*60 - $minutes*60));
// Print the result
printf("%d years, %d months, %d days, %d hours, "
. "%d minutes, %d seconds", $years, $months,
$days, $hours, $minutes, $seconds);
?>
Result is 9 years, 3 months, 2 days
HOWEVER. if I run below code, Result is 9 years, 2 months, 29days
PHP CODE 2
//差を求める日時の変数を作成
$dateTime1 = '2010-04-01';
$dateTime2 = '2019-06-30';
//DateTimeクラスで2つの日時のオブジェクトを作成
$objDatetime1 = new DateTime($dateTime1);
$objDatetime2 = new DateTime($dateTime2);
//diff()メソッドで2つの日時のオブジェクトから
//ふたつの日付の差をあらわす DateInterval オブジェクトを生成する
$objInterval = $objDatetime1->diff($objDatetime2);
//$objInterval(DateInterval オブジェクト)をformat()メソッドで日時を出力
//%Rは + や - の符号を出力するオプションです
echo $objInterval->format('%R%Y').'year<br/>'; //年
echo $objInterval->format('%R%M').'month<br/>'; //月
echo $objInterval->format('%R%D').'day<br/>'; //日
?>
9 years, 3 months, 2 days and 9 years, 2 months, 29days
what is correct?