Monday , 25 September 2023
Breaking News
Home > Tutorials > PHP > How to Calculate Days, Months and Years in PHP

How to Calculate Days, Months and Years in PHP


Friends today I am going to tell you about an interesting function of PHP that will calculate date difference between two dates. You can find days, months and years between two dates. You can use this function where you need to count days for billing or for the expiration of user etc. For example, you want to calculate days between two dates so that you generate the total bill of any user depending on his joining date and the current date, or you want to calculate total time period between two dates. You can also calculate your age with this function. So here is an example:-

when you run this script it will show you ’10’ , here one thing is to be remembered, that this function will not calculate total days from the start date, it only calculates days in current month. The second thing is “%d”, its mean days in current month. If you want to calculate months you should write this type of code.

this script will output only 1, and if you change “%m” to “%y” it will show you years. Complete result formate is as under:

Copied from PHP official site.

// Date Should In YYYY-MM-DD Format
// ‘%y Year %m Month %d Day %h Hours %i Minute %s Seconds’        =>  1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// ‘%y Year %m Month %d Day’                                     =>  1 Year 3 Month 14 Days
// ‘%m Month %d Day’                                                     =>  3 Month 14 Day
// ‘%d Day %h Hours’                                                        =>  14 Day 11 Hours
// ‘%d Day’                                                                           =>  14 Days
// ‘%h Hours %i Minute %s Seconds’                             =>  11 Hours 49 Minute 36 Seconds
// ‘%i Minute %s Seconds’                                                =>  49 Minute 36 Seconds
// ‘%h Hours                                                                        =>  11 Hours
// ‘%a Days                                                                           =>  468 Days

End of compied text.

Now we will write a simple function that will calculate days, months or years for you. Complete function is below:-

you can call this function as

this function will require two required parameters and one optional parameter. The first parameter is the first date and the second parameter is the last date and the third optional parameter is ‘d’ for days ‘m’ for months and ‘y’ for years. Remember that if you leave the third parameter it will set automatically to ‘d’.


About Muhammad Faryad

Muhammad Faryad is a professional web application developer. He has been working for 5 years in ICE786 Technologies Pvt. Ltd as a Senior Programmer and Developer. You can contact him on facebook at

Leave a Reply

Ad Test

%d bloggers like this: