PHP calculate difference between two dates WITHOUT year - php

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.

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

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));

Subtract two dates to display number of Days

<?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

Get timestamp of today and yesterday in php

How can I get the timestamp of 12 o'clock of today, yesterday and the day before yesterday by using strtotime() function in php?
12 o'clock is a variable and would be changed by user.
$hour = 12;
$today = strtotime($hour . ':00:00');
$yesterday = strtotime('-1 day', $today);
$dayBeforeYesterday = strtotime('-1 day', $yesterday);
strtotime supports a number of interesting modifiers that can be used:
$hour = 12;
$today = strtotime("today $hour:00");
$yesterday = strtotime("yesterday $hour:00");
$dayBeforeYesterday = strtotime("yesterday -1 day $hour:00");
echo date("Y-m-d H:i:s\n", $today);
echo date("Y-m-d H:i:s\n", $yesterday);
echo date("Y-m-d H:i:s\n", $dayBeforeYesterday);
It works as predicted:
2011-01-24 12:00:00
2011-01-23 12:00:00
2011-01-22 12:00:00
OO Equivalent
$iHour = 12;
$oToday = new DateTime();
$oToday->setTime($iHour, 0);
$oYesterday = clone $oToday;
$oYesterday->modify('-1 day');
$oDayBefore = clone $oYesterday;
$oDayBefore->modify('-1 day');
$iToday = $oToday->getTimestamp();
$iYesterday = $oYesterday->getTimestamp();
$iDayBefore = $oDayBefore->getTimestamp();
echo "Today: $iToday\n";
echo "Yesterday: $iYesterday\n";
echo "Day Before: $iDayBefore\n";
You can easily find out any date using DateTime object, It is so flexible
$yesterday = new DateTime('yesterday');
echo $yesterday->format('Y-m-d');
$firstModayOfApril = new DateTime('first monday of april');
echo $firstModayOfApril->format('Y-m-d');
$nextMonday = new DateTime('next monday');
echo $nextMonday->format('Y-m-d');
to get start of day yesterday
$oDate = new DateTime();
$oDate->modify('-1 day');
echo $oDate->format('Y-m-d 00:00:00');
result
2014-11-05 00:00:00
All the answers here are too long and bloated, everyone loves one-lines ;)
$yesterday = Date('Y-m-d', strtotime('-1 day'));
(Or if you are American you can randomize the date unit order to m/d/y (or whatever you use) and use Cups, galloons, feet and horses as units...)
As of PHP 7 you can write something like this:
$today = new \DateTime();
$yesterday = (clone $today)->modify('-1 day');
$dayBefore = (clone $yesterday)->modify('-1 day');
// Then call ->format('Y-m-d 00:00:00'); on each objects
you can also use new DateTime("now") for today new DateTime("1 day ago") for yesterday or all can be parse by strtotime php function.
Then format as you want.
$timeStamp = time();
// $timeStamp = time() - 86400;
if (date('d.m.Y', $timeStamp) == date('d.m.Y')) {
echo 'Today';
} elseif (date('d.m.Y', $time) == date('d.m.Y', strtotime('-1 day'))) {
echo 'Yesterday';
}

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