php DateTimeオブジェクトの変更関数を使用して、日付を月の特定の日付、つまり10日または20日などに変更しようとしています。
私は次のすべてを試しましたが、どれもうまくいきませんでした:
$d = new DateTime();
$d->modify('10th day');
$d->modify('10th');
$d->modify('10th of this month');
$d->modify('10th of the month');
php DateTimeオブジェクトの変更関数を使用して、日付を月の特定の日付、つまり10日または20日などに変更しようとしています。
私は次のすべてを試しましたが、どれもうまくいきませんでした:
$d = new DateTime();
$d->modify('10th day');
$d->modify('10th');
$d->modify('10th of this month');
$d->modify('10th of the month');
DateTime::setDateを使用します
$date = new DateTime();
$date->setDate(2001, 2, 10);
年と月がわからないと仮定すると(知っている場合はを使用DateTime::setDate()
)、これを行う1つの方法は次のようになります。
$day = 10; // 10th of the month
$dt = new DateTime('first day of this month');
$dt->modify('+' . ($day - 1) . ' days');
コンストラクターで厳密にやる方法もある気がしますが、あなたと同じように、マジックストリングがわかりませんでした。「月の最初の日」は機能しますが、「月の10日」は機能しません。
編集:どうやらコンストラクターを介してこれを行うことは不可能です。Rasmusでさえ、代わりにこの方法でそれを行うことを提案しています。
これを試して:
$d = new DateTime('first day of this month');
$d->modify('+9 day');
PS:それでも、もっと良い使い方だと思います
$cMonth = date('n');
$cYear = date('Y');
...
$d->setDate($cYear, $cMonth, 10);