Asked  7 Months ago    Answers:  5   Viewed   32 times

I got this code from Stackoverflow and changed it slightly to work with today's date.

I want to check if today fits between two dates. But this is not working. What am I missing?

$paymentDate = date('d/m/Y');
echo $paymentDate; // echos today! 
$contractDateBegin = date('d/m/Y', '01/01/2001');
$contractDateEnd = date('d/m/Y', '01/01/2015');

if ($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd)
{
  echo "is between";
}
else
{
echo "NO GO!";  
}

 Answers

84

Edit: use <= or >= to count today's date.

This is the right answer for your code. Just use the strtotime() php function.

$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today! 
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
    
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
    echo "is between";
}else{
    echo "NO GO!";  
}
Wednesday, March 31, 2021
 
SJain
answered 7 Months ago
96

You could also take a look at the DatePeriod class:

$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')
);

Which should get you an array with DateTime objects.

To iterate

foreach ($period as $key => $value) {
    //$value->format('Y-m-d')       
}
Wednesday, March 31, 2021
 
CAMason
answered 7 Months ago
24

You need to call DateInterval::format() to display that difference as a string.

echo $diff->format('%d days');

See the manual for all of the available formatting options.

Wednesday, July 7, 2021
 
mattltm
answered 4 Months ago
34
$date1 = '29/08/2013';
$date2 = '03/09/2013';

function returnDates($fromdate, $todate) {
    $fromdate = DateTime::createFromFormat('d/m/Y', $fromdate);
    $todate = DateTime::createFromFormat('d/m/Y', $todate);
    return new DatePeriod(
        $fromdate,
        new DateInterval('P1D'),
        $todate->modify('+1 day')
    );
}

$datePeriod = returnDates($date1, $date2);
foreach($datePeriod as $date) {
    echo $date->format('d/m/Y'), PHP_EOL;
}
Wednesday, August 11, 2021
 
octern
answered 3 Months ago
51

The first parameter to date_format needs to be an object of DateTime class.

echo "<td>" . date_format( new DateTime($row['date']), 'd/m/Y H:i:s' ). "</td>";

or, alternatively

echo "<td>" . date_format( date_create($row['date']), 'd/m/Y H:i:s' ). "</td>";
Monday, August 16, 2021
 
julesj
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :