我想要更改当前日期,或者我想把变量放在当前日期,如下所示:
$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.
然后我想找到这样的不同日子:
$date1=date_create($today);
$date2=date_create($oldDate);
$diff=date_diff($date1,$date2);
这可能吗?或者这是我的方式吗?
答案 0 :(得分:1)
您正试图在格式
中传递所需的日期$oldDate=$dt->format('Y-m-$day');
格式错误(如果要将字符串与变量连接起来,则应使用双quote(")
代替single(')
)
使用setDate()
方法代替。
$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);
答案 1 :(得分:1)
试试这个:使用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');