How i can change current date not all just days?

Question

I want change the current date or i want put variable in current date like this:

$companyDates = $company_dates['dates']; //this variable come from DataBase
$databaseDate=DateTime::createFromFormat("Y-m-d", $companyDates);
$day=$databaseDate->format('d'); // this is how i take just days from date format(y-m-d)

$dt = new DateTime();
$today = $dt->format('Y-m-d');
$oldDate=$dt->format('Y-m-$day'); // here i want days from database into current day month and year.

and then i want to find different day like this:

$date1=date_create($today);
$date2=date_create($oldDate);
$diff=date_diff($date1,$date2);

Is this possible OR is this my way right ?


Show source
| date   | php   | mysql   2017-01-07 10:01 2 Answers

Answers ( 2 )

  1. 2017-01-07 10:01

    You're trying to pass desired day inside format

    $oldDate=$dt->format('Y-m-$day');
    

    It's wrong format (and if you want to concatenate string with variable you should use double quote(") instead of single('))

    Use setDate() method instead of.

    $today = new DateTime();
    $oldDate = clone $today; // Clone instead creating new instance because two different DateTime instances may have different dates
    $oldDate->setDate($oldDate->format('Y'), $oldDate->format('m'), $day);
    
  2. 2017-01-07 10:01

    Try this:Use setDate

    $day=10;
    $dt = new DateTime();
    $today = $dt->format('Y-m-d');
    $out = new DateTime();
    $out->setDate($out->format('Y'), $out->format('m'), $day);
    $oldDate= $out->format('Y-m-d');
    $d1=new DateTime($oldDate);$d2=new DateTime($today);
    $difference = $d1->diff($d2);
    echo $difference->format('%r%a days');
    
◀ Go back