CODING ACADEMY

View Original

How to Calculate the Difference Between Two Dates in PHP

In this short lesson we look at how to create a Bootstrap styled form allowing the user to enter two dates. We then calculate the time difference between the two dates.

STEP 1

We will design the HTML form first:

See this content in the original post

STEP 2

We now need to add an action and method to our form.

We could process the form on the same page or send the data to a processing script.

In this case I will send my data to a processing script called processDates.php

Line 10 has been updated to reflect this.

See this content in the original post

STEP 3

We now need to create the processDates.php script.

See this content in the original post

Line 2: we check if 2 dates have been entered. Note that we should be doing more sanitization checks for a live server. You will need to amend the script depending on your individual requirements.

Lines 3 and 4: we create new DateTime objects from the supplied dates.

Line 5: we can now calculate the difference between the two dates

Line 6: a message specifying the number of days between the two dates. Note that the entered dates have been given a format of d-m-Y representing day-month-year e.g. 27-04-2016. You can change this format to suit your own requirements and date format for your own country.

Line 7: an error message displayed if 2 dates are not supplied. This is part of the IF ELSE block (line 2).