Related
How to find number of days between two dates using PHP?
$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
If you're using PHP 5.3 >, this is by far the most accurate way of calculating the absolute difference:
$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");
$abs_diff = $later->diff($earlier)->format("%a"); //3
If you need a relative (signed) number of days, use this instead:
$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");
$pos_diff = $earlier->diff($later)->format("%r%a"); //3
$neg_diff = $later->diff($earlier)->format("%r%a"); //-3
More on php's DateInterval format can be found here: https://www.php.net/manual/en/dateinterval.format.php
From PHP Version 5.3 and up, new date/time functions have been added to get difference:
$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
Result as below:
Difference: 1 years, 0 months, 2 days
DateInterval Object
(
[y] => 1
[m] => 0
[d] => 2
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 367
)
Hope it helps !
TL;DR do not use UNIX timestamps. Do not use time(). If you do, be prepared should its 98.0825% reliability fail you. Use DateTime (or Carbon).
The correct answer is the one given by Saksham Gupta (other answers are also correct):
$date1 = new DateTime('2010-07-06');
$date2 = new DateTime('2010-07-09');
$days = $date2->diff($date1)->format('%a');
Or procedurally as a one-liner:
/**
* Number of days between two dates.
*
* #param date $dt1 First date
* #param date $dt2 Second date
* #return int
*/
function daysBetween($dt1, $dt2) {
return date_diff(
date_create($dt2),
date_create($dt1)
)->format('%a');
}
With a caveat: the '%a' seems to indicate the absolute number of days. If you want it as a signed integer, i.e. negative when the second date is before the first, then you need to use the '%r' prefix (i.e. format('%r%a')).
If you really must use UNIX timestamps, set the time zone to GMT to avoid most of the pitfalls detailed below.
Long answer: why dividing by 24*60*60 (aka 86400) is unsafe
Most of the answers using UNIX timestamps (and 86400 to convert that to days) make two assumptions that, put together, can lead to scenarios with wrong results and subtle bugs that may be difficult to track, and arise even days, weeks or months after a successful deployment. It's not that the solution doesn't work - it works. Today. But it might stop working tomorrow.
First mistake is not considering that when asked, "How many days passed since yesterday?", a computer might truthfully answer zero if between the present and the instant indicated by "yesterday" less than one whole day has passed.
Usually when converting a "day" to a UNIX timestamp, what is obtained is the timestamp for the midnight of that particular day.
So between the midnights of October 1st and October 15th, fifteen days have elapsed. But between 13:00 of October 1st and 14:55 of October 15th, fifteen days minus 5 minutes have elapsed, and most solutions using floor() or doing implicit integer conversion will report one day less than expected.
So, "how many days ago was Y-m-d H:i:s"? will yield the wrong answer.
The second mistake is equating one day to 86400 seconds. This is almost always true - it happens often enough to overlook the times it doesn't. But the distance in seconds between two consecutive midnights is surely not 86400 at least twice a year when daylight saving time comes into play. Comparing two dates across a DST boundary will yield the wrong answer.
So even if you use the "hack" of forcing all date timestamps to a fixed hour, say midnight (this is also done implicitly by various languages and frameworks when you only specify day-month-year and not also hour-minute-second; same happens with DATE type in databases such as MySQL), the widely used formula
FLOOR((unix_timestamp(DATE2) - unix_timestamp(DATE1)) / 86400)
or
floor((time() - strtotime($somedate)) / 86400)
will return, say, 17 when DATE1 and DATE2 are in the same DST segment of the year; but even if the hour:minute:second part is identical, the argument might be 17.042, and worse still, 16.958 when they are in different DST segments and the time zone is DST-aware. The use of floor() or any implicit truncation to integer will then convert what should have been a 17 to a 16. In other circumstances, expressions like "$days > 17" will return true for 17.042, even if this will look as if the elapsed day count is 18.
And things grow even uglier since such code is not portable across platforms, because some of them may apply leap seconds and some might not. On those platforms that do, the difference between two dates will not be 86400 but 86401, or maybe 86399. So code that worked in May and actually passed all tests will break next June when 12.99999 days are considered 12 days instead of 13. Two dates that worked in 2015 will not work in 2017 -- the same dates, and neither year is a leap year. And between 2018-03-01 and 2017-03-01, on those platforms that care, 366 days will have passed instead of 365, making 2018 a leap year (which it is not).
So if you really want to use UNIX timestamps:
use round() function wisely, not floor().
as an alternative, do not calculate differences between D1-M1-YYY1 and D2-M2-YYY2. Those dates will be really considered as D1-M1-YYY1 00:00:00 and D2-M2-YYY2 00:00:00. Rather, convert between D1-M1-YYY1 22:30:00 and D2-M2-YYY2 04:30:00. You will always get a remainder of about twenty hours. This may become twenty-one hours or nineteen, and maybe eighteen hours, fifty-nine minutes thirty-six seconds. No matter. It is a large margin which will stay there and stay positive for the foreseeable future. Now you can truncate it with floor() in safety.
The correct solution though, to avoid magic constants, rounding kludges and a maintenance debt, is to
use a time library (Datetime, Carbon, whatever); don't roll your own
write comprehensive test cases using really evil date choices - across DST boundaries, across leap years, across leap seconds, and so on, as well as commonplace dates. Ideally (calls to datetime are fast!) generate four whole years' (and one day) worth of dates by assembling them from strings, sequentially, and ensure that the difference between the first day and the day being tested increases steadily by one. This will ensure that if anything changes in the low-level routines and leap seconds fixes try to wreak havoc, at least you will know.
run those tests regularly together with the rest of the test suite. They're a matter of milliseconds, and may save you literally hours of head scratching.
Whatever your solution, test it!
The function funcdiff below implements one of the solutions (as it happens, the accepted one) in a real world scenario.
<?php
$tz = 'Europe/Rome';
$yearFrom = 1980;
$yearTo = 2020;
$verbose = false;
function funcdiff($date2, $date1) {
$now = strtotime($date2);
$your_date = strtotime($date1);
$datediff = $now - $your_date;
return floor($datediff / (60 * 60 * 24));
}
########################################
date_default_timezone_set($tz);
$failures = 0;
$tests = 0;
$dom = array ( 0, 31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31 );
(array_sum($dom) === 365) || die("Thirty days hath September...");
$last = array();
for ($year = $yearFrom; $year < $yearTo; $year++) {
$dom[2] = 28;
// Apply leap year rules.
if ($year % 4 === 0) { $dom[2] = 29; }
if ($year % 100 === 0) { $dom[2] = 28; }
if ($year % 400 === 0) { $dom[2] = 29; }
for ($month = 1; $month <= 12; $month ++) {
for ($day = 1; $day <= $dom[$month]; $day++) {
$date = sprintf("%04d-%02d-%02d", $year, $month, $day);
if (count($last) === 7) {
$tests ++;
$diff = funcdiff($date, $test = array_shift($last));
if ((double)$diff !== (double)7) {
$failures ++;
if ($verbose) {
print "There seem to be {$diff} days between {$date} and {$test}\n";
}
}
}
$last[] = $date;
}
}
}
print "This function failed {$failures} of its {$tests} tests";
print " between {$yearFrom} and {$yearTo}.\n";
The result is,
This function failed 280 of its 14603 tests
Horror Story: the cost of "saving time"
It all began in late 2014. An ingenious programmer decided to save several microseconds off a calculation that took about thirty seconds at most, by plugging in the infamous "(MidnightOfDateB-MidnightOfDateA)/86400" code in several places. It was so obvious an optimization that he did not even document it, and the optimization passed the integration tests and somehow lurked in the code for several months, all unnoticed.
This happened in a program that calculates the wages for several top-selling salesmen, the least of which has a frightful lot more clout than a whole humble five-people programmer team taken together. On March 28th, 2015, the summer time zone engaged, the bug struck -- and some of those guys got shortchanged one whole day of fat commissions. To make things worse, most of them did not work on Sundays and, being near the end of the month, used that day to catch up with their invoicing. They were definitely not amused.
Infinitely worse, they lost the (already very little) faith they had in the program not being designed to surreptitiously shaft them, and pretended - and obtained - a complete, detailed code review with test cases ran and commented in layman's terms (plus a lot of red-carpet treatment in the following weeks).
What can I say: on the plus side, we got rid of a lot of technical debt, and were able to rewrite and refactor several pieces of a spaghetti mess that hearkened back to a COBOL infestation in the swinging '90s. The program undoubtedly runs better now, and there's a lot more debugging information to quickly zero in when anything looks fishy. I estimate that just this last one thing will save perhaps one or two man-days per month for the foreseeable future, so the disaster will have a silver, or even golden, lining.
On the minus side, the whole brouhaha costed the company about €200,000 up front - plus face, plus undoubtedly some bargaining power (and, hence, yet more money).
The guy responsible for the "optimization" had changed job in December 2014, well before the disaster, but still there was talk to sue him for damages. And it didn't go well with the upper echelons that it was "the last guy's fault" - it looked like a set-up for us to come up clean of the matter, and in the end, we remained in the doghouse for the rest of the year, and one of the team resigned at the end of that summer.
Ninety-nine times out of one hundred, the "86400 hack" will work flawlessly. (For example in PHP, strtotime() will ignore DST, and report that between the midnights of the last Saturday of October and that of the following Monday, exactly 2 * 24 * 60 * 60 seconds have passed, even if that is plainly not true... and two wrongs will happily make one right).
This, ladies and gentlemen, was one instance when it did not. As with air-bags and seat belts, you will perhaps never really need the complexity (and ease of use) of DateTime or Carbon. But the day when you might (or the day when you'll have to prove you thought about this) will come as a thief in the night (likely at 02:00 some Sunday in October). Be prepared.
Convert your dates to unix timestamps, then substract one from the another. That will give you the difference in seconds, which you divide by 86400 (amount of seconds in a day) to give you an approximate amount of days in that range.
If your dates are in format 25.1.2010, 01/25/2010 or 2010-01-25, you can use the strtotime function:
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400);
Using ceil rounds the amount of days up to the next full day. Use floor instead if you want to get the amount of full days between those two dates.
If your dates are already in unix timestamp format, you can skip the converting and just do the $days_between part. For more exotic date formats, you might have to do some custom parsing to get it right.
Easy to using date_diff
$from=date_create(date('Y-m-d'));
$to=date_create("2013-03-15");
$diff=date_diff($to,$from);
print_r($diff);
echo $diff->format('%R%a days');
See more at: https://blog.devgenius.io/how-to-find-the-number-of-days-between-two-dates-in-php-1404748b1e84
Object oriented style:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
Procedural style:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
Used this :)
$days = (strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24);
print $days;
Now it works
Well, the selected answer is not the most correct one because it will fail outside UTC.
Depending on the timezone (list) there could be time adjustments creating days "without" 24 hours, and this will make the calculation (60*60*24) fail.
Here it is an example of it:
date_default_timezone_set('europe/lisbon');
$time1 = strtotime('2016-03-27');
$time2 = strtotime('2016-03-29');
echo floor( ($time2-$time1) /(60*60*24));
^-- the output will be **1**
So the correct solution will be using DateTime
date_default_timezone_set('europe/lisbon');
$date1 = new DateTime("2016-03-27");
$date2 = new DateTime("2016-03-29");
echo $date2->diff($date1)->format("%a");
^-- the output will be **2**
You can find dates simply by
<?php
$start = date_create('1988-08-10');
$end = date_create(); // Current time and date
$diff = date_diff( $start, $end );
echo 'The difference is ';
echo $diff->y . ' years, ';
echo $diff->m . ' months, ';
echo $diff->d . ' days, ';
echo $diff->h . ' hours, ';
echo $diff->i . ' minutes, ';
echo $diff->s . ' seconds';
// Output: The difference is 28 years, 5 months, 19 days, 20 hours, 34 minutes, 36 seconds
echo 'The difference in days : ' . $diff->days;
// Output: The difference in days : 10398
Calculate the difference between two dates:
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
Output:
+272 days
The date_diff() function returns the difference between two DateTime objects.
$start = '2013-09-08';
$end = '2013-09-15';
$diff = (strtotime($end)- strtotime($start))/24/3600;
echo $diff;
I'm using Carbon in my composer projects for this and similar purposes.
It'd be as easy as this:
$dt = Carbon::parse('2010-01-01');
echo $dt->diffInDays(Carbon::now());
You can try the code below:
$dt1 = strtotime("2019-12-12"); //Enter your first date
$dt2 = strtotime("12-12-2020"); //Enter your second date
echo abs(($dt1 - $dt2) / (60 * 60 * 24));
number of days between two dates in PHP
function dateDiff($date1, $date2) //days find function
{
$diff = strtotime($date2) - strtotime($date1);
return abs(round($diff / 86400));
}
//start day
$date1 = "11-10-2018";
// end day
$date2 = "31-10-2018";
// call the days find fun store to variable
$dateDiff = dateDiff($date1, $date2);
echo "Difference between two dates: ". $dateDiff . " Days ";
If you have the times in seconds (I.E. unix time stamp) , then you can simply subtract the times and divide by 86400 (seconds per day)
$datediff = floor(strtotime($date1)/(60*60*24)) - floor(strtotime($date2)/(60*60*24));
and, if needed:
$datediff=abs($datediff);
Easiest way to find the days difference between two dates
$date1 = strtotime("2019-05-25");
$date2 = strtotime("2010-06-23");
$date_difference = $date2 - $date1;
$result = round( $date_difference / (60 * 60 * 24) );
echo $result;
$diff = strtotime('2019-11-25') - strtotime('2019-11-10');
echo abs(round($diff / 86400));
function howManyDays($startDate,$endDate) {
$date1 = strtotime($startDate." 0:00:00");
$date2 = strtotime($endDate." 23:59:59");
$res = (int)(($date2-$date1)/86400);
return $res;
}
If you want to echo all days between the start and end date, I came up with this :
$startdatum = $_POST['start']; // starting date
$einddatum = $_POST['eind']; // end date
$now = strtotime($startdatum);
$your_date = strtotime($einddatum);
$datediff = $your_date - $now;
$number = floor($datediff/(60*60*24));
for($i=0;$i <= $number; $i++)
{
echo date('d-m-Y' ,strtotime("+".$i." day"))."<br>";
}
This code worked for me and tested with PHP 8 version :
function numberOfDays($startDate, $endDate)
{
//1) converting dates to timestamps
$startSeconds = strtotime($startDate);
$endSeconds = strtotime($endDate);
//2) Calculating the difference in timestamps
$diffSeconds = $startSeconds - $endSeconds;
//3) converting timestamps to days
$days=round($diffSeconds / 86400);
/* note :
1 day = 24 hours
24 * 60 * 60 = 86400 seconds
*/
//4) printing the number of days
printf("Difference between two dates: ". abs($days) . " Days ");
return abs($days);
}
Here is my improved version which shows 1 Year(s) 2 Month(s) 25 day(s) if the 2nd parameter is passed.
class App_Sandbox_String_Util {
/**
* Usage: App_Sandbox_String_Util::getDateDiff();
* #param int $your_date timestamp
* #param bool $hr human readable. e.g. 1 year(s) 2 day(s)
* #see http://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates
* #see http://qSandbox.com
*/
static public function getDateDiff($your_date, $hr = 0) {
$now = time(); // or your date as well
$datediff = $now - $your_date;
$days = floor( $datediff / ( 3600 * 24 ) );
$label = '';
if ($hr) {
if ($days >= 365) { // over a year
$years = floor($days / 365);
$label .= $years . ' Year(s)';
$days -= 365 * $years;
}
if ($days) {
$months = floor( $days / 30 );
$label .= ' ' . $months . ' Month(s)';
$days -= 30 * $months;
}
if ($days) {
$label .= ' ' . $days . ' day(s)';
}
} else {
$label = $days;
}
return $label;
}
}
$early_start_date = date2sql($_POST['early_leave_date']);
$date = new DateTime($early_start_date);
$date->modify('+1 day');
$date_a = new DateTime($early_start_date . ' ' . $_POST['start_hr'] . ':' . $_POST['start_mm']);
$date_b = new DateTime($date->format('Y-m-d') . ' ' . $_POST['end_hr'] . ':' . $_POST['end_mm']);
$interval = date_diff($date_a, $date_b);
$time = $interval->format('%h:%i');
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60;
// display_error($seconds);
$second3 = $employee_information['shift'] * 60 * 60;
if ($second3 < $seconds)
display_error(_('Leave time can not be greater than shift time.Please try again........'));
set_focus('start_hr');
set_focus('end_hr');
return FALSE;
}
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
used the above code very simple. Thanks.
function get_daydiff($end_date,$today)
{
if($today=='')
{
$today=date('Y-m-d');
}
$str = floor(strtotime($end_date)/(60*60*24)) - floor(strtotime($today)/(60*60*24));
return $str;
}
$d1 = "2018-12-31";
$d2 = "2018-06-06";
echo get_daydiff($d1, $d2);
Using this simple function. Declare function
<?php
function dateDiff($firstDate,$secondDate){
$firstDate = strtotime($firstDate);
$secondDate = strtotime($secondDate);
$datediff = $firstDate - $secondDate;
$output = round($datediff / (60 * 60 * 24));
return $output;
}
?>
and call this function like this where you want
<?php
echo dateDiff("2018-01-01","2018-12-31");
// OR
$firstDate = "2018-01-01";
$secondDate = "2018-01-01";
echo dateDiff($firstDate,$secondDate);
?>
// Change this to the day in the future
$day = 15;
// Change this to the month in the future
$month = 11;
// Change this to the year in the future
$year = 2012;
// $days is the number of days between now and the date in the future
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);
echo "There are $days days until $day/$month/$year";
If you are using MySql
function daysSince($date, $date2){
$q = "SELECT DATEDIFF('$date','$date2') AS days;";
$result = execQ($q);
$row = mysql_fetch_array($result,MYSQL_BOTH);
return ($row[0]);
}
function execQ($q){
$result = mysql_query( $q);
if(!$result){echo ('Database error execQ' . mysql_error());echo $q;}
return $result;
}
Try using Carbon
$d1 = \Carbon\Carbon::now()->subDays(92);
$d2 = \Carbon\Carbon::now()->subDays(10);
$days_btw = $d1->diffInDays($d2);
Also you can use
\Carbon\Carbon::parse('')
to create an object of Carbon date using given timestamp string.
I have a database of events that are both "static" (on a specific day) and "recurring" (starting on a specific day, but set to be "recurring" either every week or every other week). I understand that there needs to be intervals of 7 and 14, but I don't know how to get to that point to find a date > today and spit it out.
so example;
I want to find the next upcoming recurring events and spit out their relevant dates. Side note: the data I'm stuck working with is in strings (I know, I know) of Ymd so 20150821 would be Aug 21st 2015.
if today was Aug 21 2015 and there's a recurring event for "Every other Friday" starting on Aug 7, it would be +14 which would get you to today, Friday Aug 21.
But say there was one for "Every Wednesday" starting Aug 19, I'd want to get the date for Wednesday, Aug 26 and spit that out.
This would need to work for infinite dates in the future, with the start dates never changing.
So running the script on Jan 1 2016, I'd need to know that the next "Every Wednesday" was Jan 6 2016.
pseudo code:
if(start_date < today_date) {
// start date is in the past
add recurring_inverval to start_date until result >= today_date
echo result
} elseif(start_date > today_date {
// start date is in the future
echo start_date
}
it's the adding until x that I'm lost at. not sure how to do that within an if statement.
also not sure if that's the best way to go about it. I know PHP can also do complicated strings and convert them to a date. like "Next Saturday"
I know you answered this yourself, however another option is to just use the modulus (remainder after devision) of the current date minus the start date to compute your next date. Here is a quick script to do just that :
<?php
function nextDate($start_date,$interval_days,$output_format){
$start = strtotime($start_date);
$end = strtotime(date('Y-m-d'));
$days_ago = ($end - $start) / 24 / 60 / 60;
if($days_ago < 0)return date($output_format,$start);
$remainder_days = $days_ago % $interval_days;
if($remainder_days > 0){
$new_date_string = "+" . ($interval_days - $remainder_days) . " days";
} else {
$new_date_string = "today";
}
return date($output_format,strtotime($new_date_string));
}
echo nextDate('20151210',14,'Ymd') . "<br />";
echo nextDate('20150808',14,'Ymd') . "<br />";
?>
You also don't want to return an early date if the "start date" is in the distant future. Code updated to prevent that.
solved it myself:
$begin = new DateTime($start_date); // start searching on the start date of the event
$end = new DateTime(date('Ymd')); // end on today's date
$end = $end->modify('+1 month'); // extend search to the next month
$interval = new DateInterval('P'. $freq_math .'D'); // intervals of Plus X Days - uses frequency math of 7 or 14 for every or every other
$daterange = new DatePeriod($begin, $interval, $end);
foreach($daterange as $date) {
if($date->format('Ymd') >= date('Ymd')) {
$next_recurring_date = $date->format('Ymd');
break;
}
}
echo $next_recurring_date;
Good Day,
I am trying to create a recurring date system that has the following:
nth day of nth month (2nd day of every 3rd month)
$this_months_friday = strtotime('+3 days +4 months');
the output of that will always be current day + 3 days of the 4th month.
how do I get it to display the nth day of the nth month?
since i also tried
$this_months_friday = strtotime('every 3 days +4 months');
and it did not return any result. Should i stick with strtotime on this one or move to DateTime function of php. though i wont still be able to formulate the proper argument for that kind of date sequence.
Any help would be greatly appreciated.
Thank You.
Probably better off using DateTime with a couple intervals:
$d = new DateTime();
$d->add(new DateInterVal('P' . $days . 'D'))->add('new DateInterVal('P' . $months . 'M'));
not sure what youre two example intervals are wanting.
You want an internval to start in 4 months, which then repeats every 3 days?
That'd be something more like
$d = new DateTime();
$d->add(new DateInterval('P4M')); // jump ahead 4 months immediately
$day3 = new DateInterval('P3D');
for ($i = 0; $i < 100; $i++) {
$d->add($day3); // jump ahead 3 days
... do something with this new date
}
for a basic recurring event, +4 months + 3 days, you'd simply have one interval:
$interval = new DateInteval('P4M3D'); // +4 months +3 days
$date = new DateTime();
while($some_condition) {
$date->add($interval);
do_something();
}
You can do this by saving the values in variables like that :
$day=3;
$month=4;
echo date("d-m-y",strtotime('+'.$day .'days' .'+'.$month.'months'));
Explanation:
7(july)+4 months = 11 month(November)
8 july+ 3 days = 11 july
Output:
11-11-13
NOTE: just for the example I have put the values hard coded, You can make them dynamic.
From October 1st to March 31 the fee is $1 (season 1). From April 1st to September 30 the fee is $2 (season 2).
How can I calculate the total fee of a given date range (user input) depending on how many days of this date range fall into season 1 and season 2?
The following gives me the number of days of the user´s date range, but I have no idea how to test against season 1 or season 2:
$user_input_start_date = getdate( $a );
$user_input_end_date = getdate( $b );
$start_date_new = mktime( 12, 0, 0, $user_input_start_date['mon'], $user_input_start_date['mday'], $user_input_start_date['year'] );
$end_date_new = mktime( 12, 0, 0, $user_input_end_date['mon'], $user_input_end_date['mday'], $user_input_end_date['year'] );
return round( abs( $start_date_new - $end_date_new ) / 86400 );
Given that a date range starts and ends in 2012 or starts in 2012 and ends in 2013 alone gives me 10 different possibilities of in which season a date range can start and where it can end.
There must be a better solution than iterating if/else and comparing dates over and over again for the following conditions:
Date range is completely within season 1
Date range starts in season 1 and ends in season 2
Date range starts in season 1, spans across season 2 and ends in the second part of season 1
... and so forth with "Starts in season 2", etc
This not a duplicate of How many days until X-Y-Z date? as that only deals with counting the number of days. It does not address the issue of comparing one date range with another.
The key to this problem is to simplify it as much as possible. I think using an array as a lookup table for the cost of each day of the year is the way to go. The first thing to do then, is to generate the array. The array just represents each day of the year and doesn't represent any particular year. I chose to use 2012 to generate the lookup array as it is a leap year and so has every possible day in it.
function getSeasonArray()
{
/**
* I have chosen 2012 as it was a leap year. All we want to do is
* generate an array which has avery day of the year in it.
*/
$startDate = new DateTime('1st January 2012');
//DatePeriod always drops the last day.
$endDate = new DateTime('1st January 2013');
$season2Start = new DateTime('1st April 2012');
$season2End = new DateTime('1st October 2012');
$allDays = new DatePeriod($startDate, new DateInterval('P1D'), $endDate);
$season2Days = new DatePeriod($season2Start, new DateInterval('P1D'), $season2End);
$seasonArray = array();
foreach($allDays as $day){
$seasonArray[] = $day->format('d-M');
$seasonArray[$day->format('d-M')]['season'] = 1;
}
foreach($season2Days as $day){
$seasonArray[$day->format('d-M')]['season'] = 2;
}
return $seasonArray;
}
Once that is done you just need the period over which to calculate:-
$bookingStartDate = new DateTime();//Or wherever you get this from
$bookingEndDate = new DateTime();
$bookingEndDate->setTimestamp(strtotime('+ 7 month'));//Or wherever you get this from
$bookingPeriod = new DatePeriod($bookingStartDate, new DateInterval('P1D'), $bookingEndDate);
Then we can do the calculation:-
$seasons = getSeasonArray();
$totalCost = 0;
foreach($bookingPeriod as $day){
$totalCost += $seasons[$day->format('d-M')]['season'];
var_dump($day->format('d-M') . ' = $' . $seasons[$day->format('d-M')]['season']);
}
var_dump($totalCost);
I have chosen a long booking period, so that you can scan through the var_dump() output and verify the correct price for each day of the year.
This is a quick stab done between distractions at work and I'm sure that with a bit of thought you can mould it into a more elegant solution. I'd like to get rid of the double iteration for example, unfortunately, work pressures prevent me from spending further time on this.
See the PHP DateTime man page for further information on these useful classes.
At first I suggested using the DateTime class that PHP provides, naively assuming that it has some kind of thought-out API that one could use. It turns out that it does not. While it features very basic DateTime functionality, it is mostly unusable because, for most operations, it relies on the DateInterval class. In combination, those classes represent another masterpiece of bad API design.
An interval should be defined like so:
An interval in Joda-Time represents an interval of time from one millisecond instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.
In PHP, however, an Interval is just a duration:
A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string [such as "2 days"].
Unfortunately, PHP's DateInterval definition does not allow for intersection/overlap calculation (which the OP needs) because PHP's Intervals have no specific position in the datetime continuum. Therefore, I've implemented a (very rudimentary) class that adheres to JodaTime's definition of an interval. It is not extensively tested, but it should get the work done:
class ProperDateInterval {
private $start = null;
private $end = null;
public function __construct(DateTime $start, DateTime $end) {
$this->start = $start;
$this->end = $end;
}
/**
* Does this time interval overlap the specified time interval.
*/
public function overlaps(ProperDateInterval $other) {
$start = $this->getStart()->getTimestamp();
$end = $this->getEnd()->getTimestamp();
$oStart = $other->getStart()->getTimestamp();
$oEnd = $other->getEnd()->getTimestamp();
return $start < $oEnd && $oStart < $end;
}
/**
* Gets the overlap between this interval and another interval.
*/
public function overlap(ProperDateInterval $other) {
if(!$this->overlaps($other)) {
// I haven't decided what should happen here yet.
// Returning "null" doesn't seem like a good solution.
// Maybe ProperDateInterval::EMPTY?
throw new Exception("No intersection.");
}
$start = $this->getStart()->getTimestamp();
$end = $this->getEnd()->getTimestamp();
$oStart = $other->getStart()->getTimestamp();
$oEnd = $other->getEnd()->getTimestamp();
$overlapStart = NULL;
$overlapEnd = NULL;
if($start === $oStart || $start > $oStart) {
$overlapStart = $this->getStart();
} else {
$overlapStart = $other->getStart();
}
if($end === $oEnd || $end < $oEnd) {
$overlapEnd = $this->getEnd();
} else {
$overlapEnd = $other->getEnd();
}
return new ProperDateInterval($overlapStart, $overlapEnd);
}
/**
* #return long The duration of this interval in seconds.
*/
public function getDuration() {
return $this->getEnd()->getTimestamp() - $this->getStart()->getTimestamp();
}
public function getStart() {
return $this->start;
}
public function getEnd() {
return $this->end;
}
}
It may be used like so:
$seasonStart = DateTime::createFromFormat('j-M-Y', '01-Apr-2012');
$seasonEnd = DateTime::createFromFormat('j-M-Y', '30-Sep-2012');
$userStart = DateTime::createFromFormat('j-M-Y', '01-Jan-2012');
$userEnd = DateTime::createFromFormat('j-M-Y', '02-Apr-2012');
$i1 = new ProperDateInterval($seasonStart, $seasonEnd);
$i2 = new ProperDateInterval($userStart, $userEnd);
$overlap = $i1->overlap($i2);
var_dump($overlap->getDuration());
How to find number of days between two dates using PHP?
$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
If you're using PHP 5.3 >, this is by far the most accurate way of calculating the absolute difference:
$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");
$abs_diff = $later->diff($earlier)->format("%a"); //3
If you need a relative (signed) number of days, use this instead:
$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");
$pos_diff = $earlier->diff($later)->format("%r%a"); //3
$neg_diff = $later->diff($earlier)->format("%r%a"); //-3
More on php's DateInterval format can be found here: https://www.php.net/manual/en/dateinterval.format.php
From PHP Version 5.3 and up, new date/time functions have been added to get difference:
$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
Result as below:
Difference: 1 years, 0 months, 2 days
DateInterval Object
(
[y] => 1
[m] => 0
[d] => 2
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 367
)
Hope it helps !
TL;DR do not use UNIX timestamps. Do not use time(). If you do, be prepared should its 98.0825% reliability fail you. Use DateTime (or Carbon).
The correct answer is the one given by Saksham Gupta (other answers are also correct):
$date1 = new DateTime('2010-07-06');
$date2 = new DateTime('2010-07-09');
$days = $date2->diff($date1)->format('%a');
Or procedurally as a one-liner:
/**
* Number of days between two dates.
*
* #param date $dt1 First date
* #param date $dt2 Second date
* #return int
*/
function daysBetween($dt1, $dt2) {
return date_diff(
date_create($dt2),
date_create($dt1)
)->format('%a');
}
With a caveat: the '%a' seems to indicate the absolute number of days. If you want it as a signed integer, i.e. negative when the second date is before the first, then you need to use the '%r' prefix (i.e. format('%r%a')).
If you really must use UNIX timestamps, set the time zone to GMT to avoid most of the pitfalls detailed below.
Long answer: why dividing by 24*60*60 (aka 86400) is unsafe
Most of the answers using UNIX timestamps (and 86400 to convert that to days) make two assumptions that, put together, can lead to scenarios with wrong results and subtle bugs that may be difficult to track, and arise even days, weeks or months after a successful deployment. It's not that the solution doesn't work - it works. Today. But it might stop working tomorrow.
First mistake is not considering that when asked, "How many days passed since yesterday?", a computer might truthfully answer zero if between the present and the instant indicated by "yesterday" less than one whole day has passed.
Usually when converting a "day" to a UNIX timestamp, what is obtained is the timestamp for the midnight of that particular day.
So between the midnights of October 1st and October 15th, fifteen days have elapsed. But between 13:00 of October 1st and 14:55 of October 15th, fifteen days minus 5 minutes have elapsed, and most solutions using floor() or doing implicit integer conversion will report one day less than expected.
So, "how many days ago was Y-m-d H:i:s"? will yield the wrong answer.
The second mistake is equating one day to 86400 seconds. This is almost always true - it happens often enough to overlook the times it doesn't. But the distance in seconds between two consecutive midnights is surely not 86400 at least twice a year when daylight saving time comes into play. Comparing two dates across a DST boundary will yield the wrong answer.
So even if you use the "hack" of forcing all date timestamps to a fixed hour, say midnight (this is also done implicitly by various languages and frameworks when you only specify day-month-year and not also hour-minute-second; same happens with DATE type in databases such as MySQL), the widely used formula
FLOOR((unix_timestamp(DATE2) - unix_timestamp(DATE1)) / 86400)
or
floor((time() - strtotime($somedate)) / 86400)
will return, say, 17 when DATE1 and DATE2 are in the same DST segment of the year; but even if the hour:minute:second part is identical, the argument might be 17.042, and worse still, 16.958 when they are in different DST segments and the time zone is DST-aware. The use of floor() or any implicit truncation to integer will then convert what should have been a 17 to a 16. In other circumstances, expressions like "$days > 17" will return true for 17.042, even if this will look as if the elapsed day count is 18.
And things grow even uglier since such code is not portable across platforms, because some of them may apply leap seconds and some might not. On those platforms that do, the difference between two dates will not be 86400 but 86401, or maybe 86399. So code that worked in May and actually passed all tests will break next June when 12.99999 days are considered 12 days instead of 13. Two dates that worked in 2015 will not work in 2017 -- the same dates, and neither year is a leap year. And between 2018-03-01 and 2017-03-01, on those platforms that care, 366 days will have passed instead of 365, making 2018 a leap year (which it is not).
So if you really want to use UNIX timestamps:
use round() function wisely, not floor().
as an alternative, do not calculate differences between D1-M1-YYY1 and D2-M2-YYY2. Those dates will be really considered as D1-M1-YYY1 00:00:00 and D2-M2-YYY2 00:00:00. Rather, convert between D1-M1-YYY1 22:30:00 and D2-M2-YYY2 04:30:00. You will always get a remainder of about twenty hours. This may become twenty-one hours or nineteen, and maybe eighteen hours, fifty-nine minutes thirty-six seconds. No matter. It is a large margin which will stay there and stay positive for the foreseeable future. Now you can truncate it with floor() in safety.
The correct solution though, to avoid magic constants, rounding kludges and a maintenance debt, is to
use a time library (Datetime, Carbon, whatever); don't roll your own
write comprehensive test cases using really evil date choices - across DST boundaries, across leap years, across leap seconds, and so on, as well as commonplace dates. Ideally (calls to datetime are fast!) generate four whole years' (and one day) worth of dates by assembling them from strings, sequentially, and ensure that the difference between the first day and the day being tested increases steadily by one. This will ensure that if anything changes in the low-level routines and leap seconds fixes try to wreak havoc, at least you will know.
run those tests regularly together with the rest of the test suite. They're a matter of milliseconds, and may save you literally hours of head scratching.
Whatever your solution, test it!
The function funcdiff below implements one of the solutions (as it happens, the accepted one) in a real world scenario.
<?php
$tz = 'Europe/Rome';
$yearFrom = 1980;
$yearTo = 2020;
$verbose = false;
function funcdiff($date2, $date1) {
$now = strtotime($date2);
$your_date = strtotime($date1);
$datediff = $now - $your_date;
return floor($datediff / (60 * 60 * 24));
}
########################################
date_default_timezone_set($tz);
$failures = 0;
$tests = 0;
$dom = array ( 0, 31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31 );
(array_sum($dom) === 365) || die("Thirty days hath September...");
$last = array();
for ($year = $yearFrom; $year < $yearTo; $year++) {
$dom[2] = 28;
// Apply leap year rules.
if ($year % 4 === 0) { $dom[2] = 29; }
if ($year % 100 === 0) { $dom[2] = 28; }
if ($year % 400 === 0) { $dom[2] = 29; }
for ($month = 1; $month <= 12; $month ++) {
for ($day = 1; $day <= $dom[$month]; $day++) {
$date = sprintf("%04d-%02d-%02d", $year, $month, $day);
if (count($last) === 7) {
$tests ++;
$diff = funcdiff($date, $test = array_shift($last));
if ((double)$diff !== (double)7) {
$failures ++;
if ($verbose) {
print "There seem to be {$diff} days between {$date} and {$test}\n";
}
}
}
$last[] = $date;
}
}
}
print "This function failed {$failures} of its {$tests} tests";
print " between {$yearFrom} and {$yearTo}.\n";
The result is,
This function failed 280 of its 14603 tests
Horror Story: the cost of "saving time"
It all began in late 2014. An ingenious programmer decided to save several microseconds off a calculation that took about thirty seconds at most, by plugging in the infamous "(MidnightOfDateB-MidnightOfDateA)/86400" code in several places. It was so obvious an optimization that he did not even document it, and the optimization passed the integration tests and somehow lurked in the code for several months, all unnoticed.
This happened in a program that calculates the wages for several top-selling salesmen, the least of which has a frightful lot more clout than a whole humble five-people programmer team taken together. On March 28th, 2015, the summer time zone engaged, the bug struck -- and some of those guys got shortchanged one whole day of fat commissions. To make things worse, most of them did not work on Sundays and, being near the end of the month, used that day to catch up with their invoicing. They were definitely not amused.
Infinitely worse, they lost the (already very little) faith they had in the program not being designed to surreptitiously shaft them, and pretended - and obtained - a complete, detailed code review with test cases ran and commented in layman's terms (plus a lot of red-carpet treatment in the following weeks).
What can I say: on the plus side, we got rid of a lot of technical debt, and were able to rewrite and refactor several pieces of a spaghetti mess that hearkened back to a COBOL infestation in the swinging '90s. The program undoubtedly runs better now, and there's a lot more debugging information to quickly zero in when anything looks fishy. I estimate that just this last one thing will save perhaps one or two man-days per month for the foreseeable future, so the disaster will have a silver, or even golden, lining.
On the minus side, the whole brouhaha costed the company about €200,000 up front - plus face, plus undoubtedly some bargaining power (and, hence, yet more money).
The guy responsible for the "optimization" had changed job in December 2014, well before the disaster, but still there was talk to sue him for damages. And it didn't go well with the upper echelons that it was "the last guy's fault" - it looked like a set-up for us to come up clean of the matter, and in the end, we remained in the doghouse for the rest of the year, and one of the team resigned at the end of that summer.
Ninety-nine times out of one hundred, the "86400 hack" will work flawlessly. (For example in PHP, strtotime() will ignore DST, and report that between the midnights of the last Saturday of October and that of the following Monday, exactly 2 * 24 * 60 * 60 seconds have passed, even if that is plainly not true... and two wrongs will happily make one right).
This, ladies and gentlemen, was one instance when it did not. As with air-bags and seat belts, you will perhaps never really need the complexity (and ease of use) of DateTime or Carbon. But the day when you might (or the day when you'll have to prove you thought about this) will come as a thief in the night (likely at 02:00 some Sunday in October). Be prepared.
Convert your dates to unix timestamps, then substract one from the another. That will give you the difference in seconds, which you divide by 86400 (amount of seconds in a day) to give you an approximate amount of days in that range.
If your dates are in format 25.1.2010, 01/25/2010 or 2010-01-25, you can use the strtotime function:
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400);
Using ceil rounds the amount of days up to the next full day. Use floor instead if you want to get the amount of full days between those two dates.
If your dates are already in unix timestamp format, you can skip the converting and just do the $days_between part. For more exotic date formats, you might have to do some custom parsing to get it right.
Easy to using date_diff
$from=date_create(date('Y-m-d'));
$to=date_create("2013-03-15");
$diff=date_diff($to,$from);
print_r($diff);
echo $diff->format('%R%a days');
See more at: https://blog.devgenius.io/how-to-find-the-number-of-days-between-two-dates-in-php-1404748b1e84
Object oriented style:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
Procedural style:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
Used this :)
$days = (strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24);
print $days;
Now it works
Well, the selected answer is not the most correct one because it will fail outside UTC.
Depending on the timezone (list) there could be time adjustments creating days "without" 24 hours, and this will make the calculation (60*60*24) fail.
Here it is an example of it:
date_default_timezone_set('europe/lisbon');
$time1 = strtotime('2016-03-27');
$time2 = strtotime('2016-03-29');
echo floor( ($time2-$time1) /(60*60*24));
^-- the output will be **1**
So the correct solution will be using DateTime
date_default_timezone_set('europe/lisbon');
$date1 = new DateTime("2016-03-27");
$date2 = new DateTime("2016-03-29");
echo $date2->diff($date1)->format("%a");
^-- the output will be **2**
You can find dates simply by
<?php
$start = date_create('1988-08-10');
$end = date_create(); // Current time and date
$diff = date_diff( $start, $end );
echo 'The difference is ';
echo $diff->y . ' years, ';
echo $diff->m . ' months, ';
echo $diff->d . ' days, ';
echo $diff->h . ' hours, ';
echo $diff->i . ' minutes, ';
echo $diff->s . ' seconds';
// Output: The difference is 28 years, 5 months, 19 days, 20 hours, 34 minutes, 36 seconds
echo 'The difference in days : ' . $diff->days;
// Output: The difference in days : 10398
Calculate the difference between two dates:
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
Output:
+272 days
The date_diff() function returns the difference between two DateTime objects.
$start = '2013-09-08';
$end = '2013-09-15';
$diff = (strtotime($end)- strtotime($start))/24/3600;
echo $diff;
I'm using Carbon in my composer projects for this and similar purposes.
It'd be as easy as this:
$dt = Carbon::parse('2010-01-01');
echo $dt->diffInDays(Carbon::now());
You can try the code below:
$dt1 = strtotime("2019-12-12"); //Enter your first date
$dt2 = strtotime("12-12-2020"); //Enter your second date
echo abs(($dt1 - $dt2) / (60 * 60 * 24));
number of days between two dates in PHP
function dateDiff($date1, $date2) //days find function
{
$diff = strtotime($date2) - strtotime($date1);
return abs(round($diff / 86400));
}
//start day
$date1 = "11-10-2018";
// end day
$date2 = "31-10-2018";
// call the days find fun store to variable
$dateDiff = dateDiff($date1, $date2);
echo "Difference between two dates: ". $dateDiff . " Days ";
If you have the times in seconds (I.E. unix time stamp) , then you can simply subtract the times and divide by 86400 (seconds per day)
$datediff = floor(strtotime($date1)/(60*60*24)) - floor(strtotime($date2)/(60*60*24));
and, if needed:
$datediff=abs($datediff);
Easiest way to find the days difference between two dates
$date1 = strtotime("2019-05-25");
$date2 = strtotime("2010-06-23");
$date_difference = $date2 - $date1;
$result = round( $date_difference / (60 * 60 * 24) );
echo $result;
$diff = strtotime('2019-11-25') - strtotime('2019-11-10');
echo abs(round($diff / 86400));
function howManyDays($startDate,$endDate) {
$date1 = strtotime($startDate." 0:00:00");
$date2 = strtotime($endDate." 23:59:59");
$res = (int)(($date2-$date1)/86400);
return $res;
}
If you want to echo all days between the start and end date, I came up with this :
$startdatum = $_POST['start']; // starting date
$einddatum = $_POST['eind']; // end date
$now = strtotime($startdatum);
$your_date = strtotime($einddatum);
$datediff = $your_date - $now;
$number = floor($datediff/(60*60*24));
for($i=0;$i <= $number; $i++)
{
echo date('d-m-Y' ,strtotime("+".$i." day"))."<br>";
}
This code worked for me and tested with PHP 8 version :
function numberOfDays($startDate, $endDate)
{
//1) converting dates to timestamps
$startSeconds = strtotime($startDate);
$endSeconds = strtotime($endDate);
//2) Calculating the difference in timestamps
$diffSeconds = $startSeconds - $endSeconds;
//3) converting timestamps to days
$days=round($diffSeconds / 86400);
/* note :
1 day = 24 hours
24 * 60 * 60 = 86400 seconds
*/
//4) printing the number of days
printf("Difference between two dates: ". abs($days) . " Days ");
return abs($days);
}
Here is my improved version which shows 1 Year(s) 2 Month(s) 25 day(s) if the 2nd parameter is passed.
class App_Sandbox_String_Util {
/**
* Usage: App_Sandbox_String_Util::getDateDiff();
* #param int $your_date timestamp
* #param bool $hr human readable. e.g. 1 year(s) 2 day(s)
* #see http://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates
* #see http://qSandbox.com
*/
static public function getDateDiff($your_date, $hr = 0) {
$now = time(); // or your date as well
$datediff = $now - $your_date;
$days = floor( $datediff / ( 3600 * 24 ) );
$label = '';
if ($hr) {
if ($days >= 365) { // over a year
$years = floor($days / 365);
$label .= $years . ' Year(s)';
$days -= 365 * $years;
}
if ($days) {
$months = floor( $days / 30 );
$label .= ' ' . $months . ' Month(s)';
$days -= 30 * $months;
}
if ($days) {
$label .= ' ' . $days . ' day(s)';
}
} else {
$label = $days;
}
return $label;
}
}
$early_start_date = date2sql($_POST['early_leave_date']);
$date = new DateTime($early_start_date);
$date->modify('+1 day');
$date_a = new DateTime($early_start_date . ' ' . $_POST['start_hr'] . ':' . $_POST['start_mm']);
$date_b = new DateTime($date->format('Y-m-d') . ' ' . $_POST['end_hr'] . ':' . $_POST['end_mm']);
$interval = date_diff($date_a, $date_b);
$time = $interval->format('%h:%i');
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60;
// display_error($seconds);
$second3 = $employee_information['shift'] * 60 * 60;
if ($second3 < $seconds)
display_error(_('Leave time can not be greater than shift time.Please try again........'));
set_focus('start_hr');
set_focus('end_hr');
return FALSE;
}
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
used the above code very simple. Thanks.
function get_daydiff($end_date,$today)
{
if($today=='')
{
$today=date('Y-m-d');
}
$str = floor(strtotime($end_date)/(60*60*24)) - floor(strtotime($today)/(60*60*24));
return $str;
}
$d1 = "2018-12-31";
$d2 = "2018-06-06";
echo get_daydiff($d1, $d2);
Using this simple function. Declare function
<?php
function dateDiff($firstDate,$secondDate){
$firstDate = strtotime($firstDate);
$secondDate = strtotime($secondDate);
$datediff = $firstDate - $secondDate;
$output = round($datediff / (60 * 60 * 24));
return $output;
}
?>
and call this function like this where you want
<?php
echo dateDiff("2018-01-01","2018-12-31");
// OR
$firstDate = "2018-01-01";
$secondDate = "2018-01-01";
echo dateDiff($firstDate,$secondDate);
?>
// Change this to the day in the future
$day = 15;
// Change this to the month in the future
$month = 11;
// Change this to the year in the future
$year = 2012;
// $days is the number of days between now and the date in the future
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);
echo "There are $days days until $day/$month/$year";
If you are using MySql
function daysSince($date, $date2){
$q = "SELECT DATEDIFF('$date','$date2') AS days;";
$result = execQ($q);
$row = mysql_fetch_array($result,MYSQL_BOTH);
return ($row[0]);
}
function execQ($q){
$result = mysql_query( $q);
if(!$result){echo ('Database error execQ' . mysql_error());echo $q;}
return $result;
}
Try using Carbon
$d1 = \Carbon\Carbon::now()->subDays(92);
$d2 = \Carbon\Carbon::now()->subDays(10);
$days_btw = $d1->diffInDays($d2);
Also you can use
\Carbon\Carbon::parse('')
to create an object of Carbon date using given timestamp string.