0

I want to calculate weeks,days between 2 dates.

eg: 2013-12-25 to 2013-12-25 will output 1 Day

eg: 2013-12-22 to 2013-12-25 will output 4 Days

eg: 2013-12-18 to 2013-12-25 will output 1 Week, 1 Day

eg: 2013-12-18 to 2013-12-26 will output 1 Week, 2 Days

eg: 2013-12-16 to 2013-12-30 will output 2 Weeks, 1 Day

I tried to use How to calculate the difference between two dates using PHP?

but it does not seem to work

Thanks

Community
  • 1
  • 1
Gopal
  • 861
  • 12
  • 18
  • 2
    -1 *"but not works"* is not a programming question. And all PHP date/time questions have been asked and answered already. Use the search *more*. Voting to close now. (You can gain 500 reputation if you actually discover a PHP date-time question that has not been asked before. Just ping me if you think you've found one). – hakre Dec 25 '13 at 15:39
  • possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Rajeev Ranjan Dec 25 '13 at 15:54
  • i want to show diffrence b/w dates only in weeks,days @RajeevRanjan – Gopal Dec 25 '13 at 16:00
  • week always having 7 days you can manipulate the figure of that answer. – Rajeev Ranjan Dec 25 '13 at 16:03

3 Answers3

1

i think the best way is to use timestamp, then you can calculate the seconds between 2 dates and then convert it to days and weeks.

example:

$time1; // contains seconds since 1970
$time2;

$diff=$time2-$time1;

$days=($diff % 604800)/86400;
$weeks=($diff-($days*86400))/604800;

echo $weeks $days;
Poorya Mohammadi
  • 751
  • 1
  • 8
  • 18
1

Use the DateTime::diff() function

Example:

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

Which will output:

+2 days

For more information, check this page

Jeroen Ketelaar
  • 102
  • 1
  • 6
1

If you wish to show difference only in weeks and days, use this function:

function diff_in_weeks_and_days($from, $to) {
    $day   = 24 * 3600;
    $from  = strtotime($from);
    $to    = strtotime($to) + $day;
    $diff  = abs($to - $from);
    $weeks = floor($diff / $day / 7);
    $days  = $diff / $day - $weeks * 7;
    $out   = array();
    if ($weeks) $out[] = "$weeks Week" . ($weeks > 1 ? 's' : '');
    if ($days)  $out[] = "$days Day" . ($days > 1 ? 's' : '');
    return implode(', ', $out);
}

echo diff_in_weeks_and_days('2013-12-18', '2013-12-26'); # 1 Week, 2 Days

demo

Glavić
  • 42,781
  • 13
  • 77
  • 107