This question has already been answered:

How to calculate the number of days between two dates?

In the MySQL table there are fields arrival and departure . Recorded in varchar in this form 03/14/2019 . I transfer the data through input data.

I tried this, but it does not work:

  $date1 = $post['departure']; $date2 = $post['arrival']; $diff = $date1 - $date2; echo $diff; 

Reported as a duplicate by Ipatiev php Mar 13 at 10:11 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • tried so it does not work $ date1 = $ post ['departure']; $ date2 = $ post ['arrival']; $ diff = $ date1 - $ date2; echo $ diff; - Name

4 answers 4

recorded in varchar in this form 03/14/2019.

It is not right. The date should be recorded in the database in the format 2019-03-13.
Therefore, before writing to the database, it must be reformatted.

after that, the difference can be obtained directly in the request:

 SELECT to_days(departure) - to_days(arrival) as duration, ... 

    An example is taken from here :

     # Первое значение # Так же можно вставить вашу дату из <input> $datetime1 = new DateTime('2009-10-11'); # Второе значение $datetime2 = new DateTime('2009-10-13'); $interval = $datetime1->diff($datetime2); echo $interval->format('%R%a дней'); 
        abs ( floor( (strtotime(date2) - strtotime(date1)) / 24*3600 ) ) 
      • you have an inaccuracy - you need seconds in brackets to take. - Jigius

      This is best done not by php, but by the means of MySQl itself in the request. For example, something like:

      select DATEDIFF (DATE_FORMAT (arrival, '% d /% m /% Y'), DATE_FORMAT (departure, '% d /% m /% Y')) as duration from tablename;

      • This request will return the full nonsense - Ipatiev