So, I have some time values:
$year = 2017; $month = 2; $day = 16; $hour = 7; $minute = 24; $second = 10;
Does PHP have a natural way to get a DateTimeImmutable object from that?
Is it this?
$datetime = new DateTime; // Create DateTime for current time
$datetime->setDate($year, $month, $day);
$datetime->setTime($hour, $minute, $second);
$datetime = DateTimeImmutable::createFromMutable($datetime);
The constructor only takes a string. The manual describes several formats, but none of them is an ISO date or something like that. Am I supposed to choose one arbitrarily, for example "WDDX" (because it doesn't require me to pad values), and format my date accordingly?
$datetime = DateTimeImmutable($year.'-'.$month.'-'.$day.'T'.$hour.':'.$minute.':'.$second$);
All these ways feel rather cumbersome. How is this usually done?
Edit: I just found another way (the documentation didn't make that easy) that feels quite right:
$datetime = DateTimeImmutable::createFromFormat(DateTimeImmutable::ATOM, $year.'-'.$month.'-'.$day.'T'.$hour.':'.$minute.':'.$second.'+00:00');
You could try something like this:
$time = (new DateTimeImmutable)
->setTime($hour, $minute, $second)
->setDate($year, $month, $day);
It's a little bit "shorter" variant of your first example code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With