MOCKSTACKS
EN
Questions And Answers

More Tutorials









PHP difference between two dates


The most feasible way is to use, the DateTime class.
An example:


<?php
// Create a date time object, which has the value of ~ two years ago
$twoYearsAgo = new DateTime("2020-02-21 20:05:56");
// Create a date time object, which has the value of ~ now
$now = new DateTime("202-02-21 02:55:07");
// Calculate the diff
$diff = $now->diff($twoYearsAgo);
// $diff->y contains the difference in years between the two dates
$yearsDiff = $diff->y;
// $diff->m contains the difference in minutes between the two dates
$monthsDiff = $diff->m;
// $diff->d contains the difference in days between the two dates
$daysDiff = $diff->d;
// $diff->h contains the difference in hours between the two dates
$hoursDiff = $diff->h;
// $diff->i contains the difference in minutes between the two dates
$minsDiff = $diff->i;
// $diff->s contains the difference in seconds between the two dates
$secondsDiff = $diff->s;
// Total Days Diff, that is the number of days between the two dates
$totalDaysDiff = $diff->days;
// Dump the diff altogether just to get some details ;)
var_dump($diff);
?>

Also, comparing two dates is much easier, just use the Comparison operators , like:


<?php
// Create a date time object, which has the value of ~ two years ago
$twoYearsAgo = new DateTime("2020-02-21 20:05:56");
// Create a date time object, which has the value of ~ now
$now = new DateTime("2022-02-21 02:55:07");
var_dump($now > $twoYearsAgo); // prints bool(true)
var_dump($twoYearsAgo > $now); // prints bool(false)
var_dump($twoYearsAgo <= $twoYearsAgo); // prints bool(true)
var_dump($now == $now); // prints bool(true)
?>


Conclusion

In this page (written and validated by ) you learned about PHP difference between two dates . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Control Structures.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.