ItSolutionStuff.com

How to Get Difference Between Two Dates in PHP?

By Hardik Savani • May 14, 2024
PHP

Do you want to calculate difference between two dates in php? I mean difference between two dates in days, months, years using php. if yes than i will show you to php get difference between two dates using strtotime(), abs() and floor().

We may sometime require to get difference between in php for your application, even if you use any php framework like laravel, codeigniter, wordpress but you can use code php code anywhere. So you can see following examples.

Bellow examples will help you to calculate difference between two dates in php example.

I will give you one by one simple example of following definition.

1) PHP Calculate difference between two dates in days

2) PHP Calculate difference between two dates in months

3) PHP Calculate difference between two dates in years

Example:

<?php

$startDate = "2018-05-20";

$endDate = "2019-08-27";

$diffData = abs(strtotime($endDate) - strtotime($startDate));

$yearsDiff = floor($diffData / (365*60*60*24));

print_r("Years:".$yearsDiff);

$monthsDiff = floor(($diffData - $yearsDiff * 365*60*60*24) / (30*60*60*24));

print_r(" Months:".$monthsDiff);

$daysDiff = floor(($diffData - $yearsDiff * 365*60*60*24 - $monthsDiff*30*60*60*24)/ (60*60*24));

print_r(" Days:".$daysDiff);

Output:

Years:1 Months:3 Days:9

I hope it can help you...

Tags: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Change Date Format in PHP?

Read Now →

How to Convert String to Date in PHP?

Read Now →

PHP CURL Post Request with Parameters Example

Read Now →

PHP JQuery Ajax Post Request Example

Read Now →

How to Change Date Format in Codeigniter?

Read Now →

PHP MySQL Column Sorting Example Tutorial

Read Now →

PHP MySQL DataTables Server-side Processing Example

Read Now →

PHP Ajax Infinite Scroll Pagination Example

Read Now →

JQuery Datepicker Example using JQuery UI JS

Read Now →

MySQL Calculate Age from Date of Birth Example

Read Now →

How to Add JQuery Modal Popup in PHP?

Read Now →

How to Get Month Difference Between Two Dates in Laravel?

Read Now →

How to Find Day Name from Specific Date in PHP?

Read Now →

How to Get Difference Between Two Dates in Laravel?

Read Now →