Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Best way to get a DateTimeImmutable object for a specific time

Tags:

php

datetime

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');
like image 697
AndreKR Avatar asked Oct 27 '25 10:10

AndreKR


1 Answers

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

like image 145
Skysplit Avatar answered Oct 29 '25 02:10

Skysplit