なにがしたい?
DateTimeのインスタンスに'2024-01-01 01:23:45'が入っていたとして、ここから秒だけ削除して'2024-01-01 01:23:00'にしたい。
どれがいいだろう?
$dt = new \DateTimeImmutable('2024-01-01 01:23:45');
// その1
$dt2 = new \DateTimeImmutable($dt->format('Y-m-d H:i:00'));
// その2
$dt2 = $dt->setTime($dt->format('H'), $dt->format('i'), 0);
// その3
$dt2 = $dt->setTimestamp(intdiv($dt->getTimestamp(), 60) * 60);
// その4
$dt2 = $dt->sub(new DateInterval(sprintf('PT%dS', $dt->format('s'))));
どれも不毛感がすごい。
DateTimeImmutable::setTimeで秒だけ指定できないかと思ったのですが、何故か引数$hour
・$minute
が必須となっているため駄目でした。
$dt = $dt->setTime(second: 0);
// PHP Fatal error: DateTimeImmutable::setTime(): Argument #1 ($hour) not passed
$dt = $dt->setTime(null, null, 0);
// Deprecated: DateTimeImmutable::setTime(): Passing null to parameter #1 ($hour) of type int is deprecated
// 00:00:00になる
どうして。
一番有望そうだったmodifyにも、相対指定の方法は数あるものの、任意の値に設定するような方法は見当たらないようでした。
汎用性を考えると、やはりその1の一度format
で出力して再度newするのが最も手っ取り早いですかね。
しかし、せっかくできているインスタンスを捨てて一度文字列に戻すのって微妙過ぎる。
結局どうすればいい?
いちいち消さずにそのまま持っておいて、出力時にformat指定すればいいんじゃないかな。