0

I tried with the below code to find the difference between two dates which is passed through post variable and print, but failed.

$fromdate=$_POST['from_date']; $todate=$_POST['to_date']; $date1 = new DateTime($fromdate); //inclusive $date2 = new DateTime($todate); //exclusive $diff = $date2->diff($date1); echo $diff;

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Nayan Patel
  • 1,683
  • 25
  • 27
  • possible duplicate of [Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...](http://stackoverflow.com/a/18602474/67332) – Glavić Nov 02 '14 at 20:53

1 Answers1

0

Something like this should work for you:

<?php

    $_POST['from_date'] = "2014-10-01";
    $_POST['to_date'] = "2014-11-02";

    $fromdate = $_POST['from_date'];
    $todate = $_POST['to_date'];

    $diff = abs(strtotime($fromdate) - strtotime($todate));

    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

    printf("%d years, %d months, %d days\n", $years, $months, $days);

?>

Output:

0 years, 1 months, 2 days 
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • it's a very unhelpful feature of all StackExchange sites. I can only say that it perfectly resembles the flaws of human society. Hope you have a thick skin.. – captcha Nov 02 '14 at 21:08
  • Probably because not all years have 365 days, and not all months have 30 days. – Glavić Nov 03 '14 at 14:59