PHP Date Difference in Days, Hours, Minutes, and SecondsPHP Date Difference in Days, Hours, Minutes, and Seconds

To get PHP Date Time Difference in Days, Hours, Minutes, and Seconds we use three major PHP built-in things DateTime object, date_create() function, and date_diff() function.

We also use DateTimeZone object to get specific timezone date and time and calculate differnce between two dates.

PHP Date Difference in Days, Hours, Minutes, and Seconds
PHP Date Difference in Days, Hours, Minutes, and Seconds

Introduction

date_create() function is used get DateTime object and also you can format date and time accordingly.

Syntax:

Output: 2021/04/25

date_diff() function is helps to get difference between two DateTime object.

Syntax:

Output:

DateInterval Object ( [y] => 1 [m] => 4 [d] => 13 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 1 [days] => 500 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )

PHP Date Time Difference in Days, Hours, Minutes, and Seconds With Example

To compile it go there https://codingtasks.net/php-online-editor/ and copy paste the above code.

Output:

Year: 1
Month: 6
Days: 6
Hours: 7
Minutes: 37
Seconds: 39

Code Highlights:

  1. On the first line, we set the time zone using DateTimeZone( $userTimezone ) object and if you do not specify it, it takes the default time zone.
  2. Then we get the current time of the specified time zone by using DateTime(date('m/d/y h:i:s a'),$timezone) object.
  3. After that, we get our start date and end date using date_create() function for the specific format to get the difference.
  4. Now we get the difference between two dates in PHP by using the date_diff() function.

I hope you got it completely.

To know more about PHP date and date difference you can check https://www.php.net/manual/en/function.date-diff.php

Also Check:

Happy Coding..!

Was this article helpful?
YesNo

By Bikash

My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP.

5 thoughts on “Get PHP Date Time Difference in Days, Hours, Minutes, and Seconds”

Leave a Reply

Your email address will not be published. Required fields are marked *