DateTime :: modify()的表达式可以更改日期

Álv*_*lez 3 php datetime

我有一个DateTime对象,我需要将它移动到X月的第二天.例如,如果X是15:

2011-02-03⇒2011-02-15#早于15,留在这个月

2011-02-15⇒2011-02-15#今天是15,今天留下来

2011-02-20⇒2011-03-15#晚于15,转移到下个月

我知道我可以使用的组合DateTime::format()DateTime::setDate(),但有可能使其通过一个调用DateTime::modify()

!它也必须工作PHP/5.2.14.

包含" 第15天 "的表达式甚至不解析.

Ced*_*ric 10

$x = 15; // day 15 of the month
$d = $date->format('d');
$m = $date->format('m');
$y = $date->format('Y');

$date->setDate($y , $m , $x); // set the wanted day for the month

//if the wanted day was before the current day, add one month
if( $d > $x ){ // is next month's one.
   $date->modify($date, '+1 month');
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,正如戈登所提到的,条件更容易 (2认同)