# How Many Days Since a Date and other Calculations

Here i calculate the number of days since a certain date in php and use the values for checking how much something costs per day.

## Start Date

Lets add the date that the item was purchaced. In date format Year-Month-Day

`\$date_start = date_create("2017-10-29");`

## Today's Date

Get todays date according to the server date with php

`\$todays_date = date_create(date('Y-m-d'));`

## Check the difference between the dates

Using the date_diff function we can check the difference between these dates.

`\$diff = date_diff(\$date_start,\$todays_date);`

## Output the details

I usually like to add all the data into a variable and then return it so here we will add all the data to the variable \$template_result. This will give us the amount of days since the original date.

`\$template_result = 'Number of Days Since 29th October 2017 is '.\$diff->format("%a");`

## More Calculations

Using this number we can calculate different things like how many years or months since a date.

## Years Since Calculation

Calculate the Years since the date.

`\$years_calc = \$diff->format("%a") / 365;\$years_calc = number_format(\$years_calc, 2);\$template_result .= "<p>Years \$years_calc </p>";`

## Cost per Day

If the item has an original value we can then calculate the cost per day using the original number.

`\$cost = 331;\$per_day = \$cost / \$diff->format("%a");\$per_day = number_format(\$per_day, 2);\$template_result .= "<p>Original Total Cost: \$\$cost, Cost per Day \$\$per_day </p>";`

## Return the results

Now we can just return the results or just echo them.

`echo \$template_result;`

You can see a working demo below.

## Demo

Number of Days Since 29th October 2017 is 630

Years 1.73

Original Total Cost: \$331, Cost per Day \$0.53

##### Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹