Subtract two dates to display number of Days - php

<?php
$datetime1 = new DateTime("$da[tofollowon]");
$datetime2 = new DateTime();
$difference = $datetime1->diff($datetime2);
$days = $difference->days;
?>
Above php code displays difference in two dates, but i want to subtract these two dates datetime2 from datetime1 which should even display negative values.

Try this
$d1 = strtotime("2014-01-10"); // or your date as well
$d2 = strtotime("2014-01-01");
$datediff = $d1 - $d2;
echo floor($datediff/(60*60*24)).' days';

try
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400);
For more :- Finding the number of days between two dates

Related

Days between two dates doesn't work in PHP

I need to compute the days between two dates (format YYYYMMDD)
I used two test dates, 2020-01-20 and 2020-02-20
$enddate = "20200220";
$startdate = "20200120";
$s = new DateTime($enddate);
$e = new DateTime($startdate);
$diff = $s->diff($e);
echo "days: ".$diff->d;
the result is 0 instead of being a month worth of days
days: 0
I understand that dates as strings might be ambiguous, so I also tried to specify the format, by doing:
$enddate = "20200220";
$startdate = "20200120";
$s = DateTime::createFromFormat('Ymd', $startdate);
$e = DateTime::createFromFormat('Ymd', $enddate);
$diff = $s->diff($e);
echo "days: ".$diff->d;
Still got 0
days: 0
You can use strtotime
<?php
// strtotime converts any string date format to unix time
$date1 = "2020-01-20";
$date2 = "2020-02-20";
$seconds_in_a_day = 86400;
$diff = (strtotime($date2) - strtotime($date1))/$seconds_in_a_day;
echo $diff; // output 31

Duration between two times in PHP MySQL

I have 5 fields in one of my mysql tables. 3 of them are date, time1 and time2. date is DATE data type and time1 and time2 are TIME data type. I want to calculate the interval between time1 and time2, and display in the internet browser. I tried as follows in PHP,but it didn't work.
$start_time = strtotime($row['time1']);
$end_time = strtotime($row['time2']);
$interval = $end_time - $start_time;
Do I have to combine date and time in one field and store as timestamp?
Thanks.
you can try somethig like this:
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
$interval->format($differenceFormat);
reff :http://php.net/manual/en/function.date-diff.php
You can also try this using DateTime class
$date_time1 = new DateTime('09:00:59');
$date_time2 = new DateTime('09:01:00');
$interval = $date_time1->diff($date_time2);
$interval->format('%s seconds(s)');
$start_time = strtotime($row['time1']);
$end_time = strtotime($row['time2']);
$ts1 = strtotime(str_replace('/', '-', $start_time));
$ts2 = strtotime(str_replace('/', '-', $end_time));
$diff = abs($ts1 - $ts2) / 3600;

calculate number of days between 2 dates in php

I need to calculate difference between 2 dates here is my dates
$start = strtotime('17/05/2016');
$end = strtotime('12/05/2016');
I have tried
echo $days_between = ceil(abs($end - $start) / 86400);
But it shows output as 17140
Hep to find the number of days between 2 given dates
You just need to specify what is the date format, so:
$date1 = DateTime::createFromFormat('d/m/Y',"12/05/2016");
$date2 = DateTime::createFromFormat('d/m/Y',"17/05/2016");
echo $diff = $date2->diff($date1)->format("%a"); //output: 5
You need to change the format:
with d/m/Y at m/d/Y
You can also use a format like this:
$s = DateTime::createFromFormat('d/m/Y', '17/05/2016');
$d = DateTime::createFromFormat('d/m/Y', '05/12/2016');
And get the difference of days:
$start = DateTime::createFromFormat('d/m/Y', '17/05/2016');
$end = DateTime::createFromFormat('d/m/Y', '12/05/2016');
$interval = $end->diff($start);
$days = $interval->format('%a');
You are using a wrong format for dates, the original is: "Y-m-d" not "d/m/Y", you can use something like this if you could change the date format:
$now = strtotime("2016-05-17"); // or your date as well
$your_date = strtotime("2016-05-12");
$datediff = $now - $your_date;
echo floor($datediff/(60*60*24));

PHP calculate difference between two dates WITHOUT year

I generally use this method to calculate difference between two dates:
$datediff = strtotime($enddate) - strtotime($startdate);
$totalDays = floor($datediff/(60*60*24));
But now I got a problem. Now I should not consider the year in the calculation. Which means for example the difference between two dates January 2 2014 and January 6 2015 should give me result as 4 days.
For that I changed the date format to m-d, and used the below method:
$startdate = date('m-d',strtotime($startdate));
$enddate = date('m-d',strtotime($enddate));
$datediff = $enddate - $startdate;
$totalDays = floor($datediff/(60*60*24));
But I get the result as 0. Can anyone help me? What is the mistake I am doing?
You can replace the year with 1970 and do the calculations against that.
$date1 = '2014-01-17 04:05:54';
$date2 = '2013-01-12 02:07:54';
$date1 = preg_replace('/([\d]{4})/', '1970', $date1);
$date2 = preg_replace('/([\d]{4})/', '1970', $date2);
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
$date_diff = gmdate('d H:i:s', abs($timestamp2-$timestamp1));
var_dump($date_diff);
Please try this :
$startdate = 'January 1 2014';
$enddate = 'February 6 2015';
$startdate = date('d-m-1970',strtotime($startdate));
$enddate = date('d-m-1970',strtotime($enddate));
$datediff = strtotime($enddate) - strtotime($startdate);
$totalDays = floor($datediff/(60*60*24));
echo $totalDays;
Hope this will help
here is the php DateTime solution
$date1 = new DateTime('2015-01-02');
$date2 = new DateTime('2014-01-06');
switch (true) {
case ($date1 < $date2) :
$date2->setDate($date1->format('Y'), $date2->format('m'), $date2->format('d'));
break;
case ($date2 < $date1) :
$date1->setDate($date2->format('Y'), $date1->format('m'), $date1->format('d'));
break;
}
$interval = $date1->diff($date2);
echo $interval->format('%R%a days'); // +4 days
have fun!
Or just cut off the year and leave away the switch part.
Just take the "m-d" part of your date and append any year onto the end of it, e.g. "-2014". The datediff() will then give you the required answer.

Elegant way to get the count of months between two dates?

Let's assume I have two dates in variables, like
$date1 = "2009-09-01";
$date2 = "2010-05-01";
I need to get the count of months between $date2 and $date1($date2 >= $date1). I.e. i need to get 8.
Is there a way to get it by using date function, or I have to explode my strings and do required calculations?
Thanks.
For PHP >= 5.3
$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-05-01");
var_dump($d1->diff($d2)->m); // int(4)
var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8)
DateTime::diff returns a DateInterval object
If you don't run with PHP 5.3 or higher, I guess you'll have to use unix timestamps :
$d1 = "2009-09-01";
$d2 = "2010-05-01";
echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8
But it's not very precise (there isn't always 30 days per month).
Last thing : if those dates come from your database, then use your DBMS to do this job, not PHP.
Edit: This code should be more precise if you can't use DateTime::diff or your RDBMS :
$d1 = strtotime("2009-09-01");
$d2 = strtotime("2010-05-01");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;
while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
$i++;
}
echo $i; // 8
Or, if you want the procedural style:
$date1 = new DateTime("2009-09-01");
$date2 = new DateTime("2010-05-01");
$interval = date_diff($date1, $date2);
echo $interval->m + ($interval->y * 12) . ' months';
UPDATE: Added the bit of code to account for the years.
Or a simple calculation would give :
$numberOfMonths = abs((date('Y', $endDate) - date('Y', $startDate))*12 + (date('m', $endDate) - date('m', $startDate)))+1;
Accurate and works in all cases.
This is another way to get the number of months between two dates:
// Set dates
$dateIni = '2014-07-01';
$dateFin = '2016-07-01';
// Get year and month of initial date (From)
$yearIni = date("Y", strtotime($dateIni));
$monthIni = date("m", strtotime($dateIni));
// Get year an month of finish date (To)
$yearFin = date("Y", strtotime($dateFin));
$monthFin = date("m", strtotime($dateFin));
// Checking if both dates are some year
if ($yearIni == $yearFin) {
$numberOfMonths = ($monthFin-$monthIni) + 1;
} else {
$numberOfMonths = ((($yearFin - $yearIni) * 12) - $monthIni) + 1 + $monthFin;
}
I use this:
$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-09-01");
$months = 0;
$d1->add(new \DateInterval('P1M'));
while ($d1 <= $d2){
$months ++;
$d1->add(new \DateInterval('P1M'));
}
print_r($months);
Using DateTime, this will give you a more accurate solution for any amount of months:
$d1 = new DateTime("2011-05-14");
$d2 = new DateTime();
$d3 = $d1->diff($d2);
$d4 = ($d3->y*12)+$d3->m;
echo $d4;
You would still need to handle the leftover days $d3->d if your real world problem is not as simple and cut and dry as the original question where both dates are on the first of the month.
This is a simple method I wrote in my class to count the number of months involved into two given dates :
public function nb_mois($date1, $date2)
{
$begin = new DateTime( $date1 );
$end = new DateTime( $date2 );
$end = $end->modify( '+1 month' );
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($begin, $interval, $end);
$counter = 0;
foreach($period as $dt) {
$counter++;
}
return $counter;
}
In case the dates are part of a resultset from a mySQL query, it is much easier to use the TIMESTAMPDIFF function for your date calculations and you can specify return units eg. Select TIMESTAMPDIFF(MONTH, start_date, end_date)months_diff from table_name
strtotime is not very precise, it makes an approximate count, it does not take into account the actual days of the month.
it's better to bring the dates to a day that is always present in every month.
$date1 = "2009-09-01";
$date2 = "2010-05-01";
$d1 = mktime(0, 0, 1, date('m', strtotime($date1)), 1, date('Y', strtotime($date1)));
$d2 = mktime(0, 0, 1, date('m', strtotime($date2)), 1, date('Y', strtotime($date2)));
$total_month = 0;
while (($d1 = strtotime("+1 MONTH", $d1)) <= $d2) {
$total_month++;
}
echo $total_month;
I have used this and works in all conditions
$fiscal_year = mysql_fetch_row(mysql_query("SELECT begin,end,closed FROM fiscal_year WHERE id = '2'"));
$date1 = $fiscal_year['begin'];
$date2 = $fiscal_year['end'];
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$te=date('m',$ts2-$ts1);
echo $te;

Categories