1

I have a code running wherein I take dates as input and try to get the difference of days between these two dates.

Tried various options but the result does not make sense

Input

<form method="post" action="date_Results.php">
    <input class="span2 ui-autocomplete-input" value="" id="start_date"     name="start_date" autocomplete="off" type="text">
    <input class="span2 ui-autocomplete-input" value="" id="end_date" name="end_date" autocomplete="off" type="text">
</form>

date_Results.php

<?php  
var_dump($_POST);
date_default_timezone_set('Europe/Amsterdam');
$D1 = $_POST['start_date'];
$D2 = $_POST['end_date'];

$frmt_D1 = $D1;
$frmt_D2 = $D2;

$date = new Datetime($frmt_D1);
$now = new Datetime($frmt_D2);

echo $date->diff($now)->format("%d");
?>

Result

array (size=2)
  'start_date' => string '13-07-2017' (length=10)
  'end_date' => string '01-09-2017' (length=10)

19 ??? days for these two inputs

The result is correct when queried for dates within the same month

array (size=2)
  'start_date' => string '12-07-2017' (length=10)
  'end_date' => string '24-07-2017' (length=10)

12

Even with date format change, result is not what it should be

array (size=2)
  'start_date' => string '2017-07-13' (length=10)
  'end_date' => string '2017-12-31' (length=10)

18
u_mulder
  • 54,101
  • 5
  • 48
  • 64
Rajiv S Mehta
  • 50
  • 2
  • 7
  • That is not how the `format()` method works. It does not compute new values depending on the format string you supply, it only formats the given numbers according to the format. You picked only the "day" component of the date and ignored the rest. – arkascha Jul 13 '17 at 14:56
  • 1
    http://php.net/manual/en/dateinterval.format.php - You want `%a`, not `%d`. `%d` is good for when you want to say `X years, Y months, and Z days` – aynber Jul 13 '17 at 14:57
  • Thanks very much, getting a little lost with this new way , OOPS... quite used to procedural way, but was getting humongous errors with that also. %a did it. – Rajiv S Mehta Jul 13 '17 at 15:09

0 Answers0