Avatar of BR
BR
Flag for Turkey asked on

php date function ( diffrence between two dates )

Dear Experts,

I'd like to find the time duration in days and months between two dates.

I have two dates

echo $today = date('Y-m-d');
echo "<br>";
echo $seconddate =  "2017-10-18";
echo "<br>";
echo $diffrence = ($seconddate - $today);

Open in new window


but it doesn't work. what should I do?
PHP

Avatar of undefined
Last Comment
BR

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Thomas

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SniperCode Sheva

Hello, try this:

<?php
$date1 = "now";
$date2 = "2017-10-18";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);
?>

Open in new window

BR

ASKER
thank you SniperCode Sheva
SniperCode Sheva

You are welcome.
Your help has saved me hundreds of hours of internet surfing.
fblack61
Ray Paseur

The correct answer here is the first comment from Thomas.  It's an anti-practice to write your own date/time arithmetic, especially because it will often be wrong in months that do not have 30 days, in leap years, or across daylight savings time.  Instead use the built-in PHP functionality.

You can learn more about the ways we handle date/time values in this article.
https://www.experts-exchange.com/articles/20920/Handling-Time-and-Date-in-PHP-and-MySQL-OOP-Version.html

You can get better answers here at E-E if you search the articles first, and if you leave your questions open a bit longer.  I would recommend leaving your questions open for at least 24 hours.

I do not recommend using the accepted solution in a deployed application.
BR

ASKER
Thank you Ray Paseur
You are right
Thank you very much

I will use the first answer