-1

Possible Duplicate:
How to find number of days between two dates using php

Collect the number of days between two dates, for example 02/11/2012 And between 02/12/2012

The result is the number of days = 1 day

Community
  • 1
  • 1
Eng Kam
  • 11
  • 2
  • You've tagged this AJAX and PHP. Do you need to know how to do this in Javascript, or PHP? – ghoti Jun 02 '12 at 19:47

4 Answers4

2

try this

function dateDiff ($d1, $d2) {

  return round(abs(strtotime($d1)-strtotime($d2))/86400);

} 

The function uses the PHP ABS() absolute value to always return a postive number as the number of days between the two dates.

Moyed Ansari
  • 8,436
  • 2
  • 36
  • 57
2

PHP >= 5.3 you can use DateTime::Diff:

<?php
  $datetime1 = new DateTime('2009-10-11');
  $datetime2 = new DateTime('2009-10-13');
  $interval = $datetime1->diff($datetime2);
  echo $interval->format('%R%a days');
?>
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • This is probably significantly slower than using strtotime(), but it is an alternative ;) – Jeroen Jun 02 '12 at 19:49
  • @Jeroen: Although does take in to account DST/Leap Years and other factors... – Brad Christie Jun 02 '12 at 19:50
  • What difference would that make? UNIX timestamps as returned by strtotime() is simply the amount of seconds since jan 1 1970, so that automatically 'takes into account' leap years. – Jeroen Jun 02 '12 at 19:52
  • @Jeroen: That comment was in regards to manipulating the `DateTime` object, which I feel is more reliable than basing calculations off each day having 86400 seconds. The DateTime object (and its advancements with PHP 5.3) are more stable; that's all I was getting at. – Brad Christie Jun 02 '12 at 20:00
  • Of course, if you're gonna be manipulating it, this is the way to go. – Jeroen Jun 02 '12 at 20:04
0
echo (strtotime('02/12/2012') - strtotime('02/11/2012')) / (24*60*60);

This line converts both dates to unix timestamps, subtracts them and divides this by the amount of seconds in a day.

Jeroen
  • 13,056
  • 4
  • 42
  • 63
0

You can convert your date to a timestamp with the strtotime() function:

$date1 = strtotime("02/11/2012");
$date2 = strtotime("02/12/2012");
$difference = $date1 - $date2;

Then you have the difference in seconds which is a new timestamp, so you can convert this to days with the date() function:

$days = date("d", $difference);
Stefan Fandler
  • 1,141
  • 7
  • 13