所以,我有一些时间值:
$year = 2017; $month = 2; $day = 16; $hour = 7; $minute = 24; $second = 10;
PHP有一种自然的方式从中获取DateTimeImmutable对象吗?
这是吗?$datetime = new DateTime; // Create DateTime for current time
$datetime->setDate($year, $month, $day);
$datetime->setTime($hour, $minute, $second);
$datetime = DateTimeImmutable::createFromMutable($datetime);
构造函数只接受一个字符串。 manual描述了几种格式,但它们都不是ISO日期或类似的东西。我应该随意选择一个,例如“WDDX”(因为它不需要我填充值),并相应地格式化我的日期?
$datetime = DateTimeImmutable($year.'-'.$month.'-'.$day.'T'.$hour.':'.$minute.':'.$second$);
所有这些方式都感觉相当麻烦。这通常是怎么做的?
编辑:我刚刚找到另一种方式(文档没那么简单)感觉非常正确:
$datetime = DateTimeImmutable::createFromFormat(DateTimeImmutable::ATOM, $year.'-'.$month.'-'.$day.'T'.$hour.':'.$minute.':'.$second.'+00:00');
答案 0 :(得分:2)
您可以尝试这样的事情:
$time = (new DateTimeImmutable)
->setTime($hour, $minute, $second)
->setDate($year, $month, $day);
这是您的第一个示例代码
的一个“更短”变体答案 1 :(得分:2)
您可以使用mktime和DateTimeImmutable::setTimestamp
$year = 2017; $month = 2; $day = 16; $hour = 7; $minute = 24; $second = 10;
$datetime = (new DateTimeImmutable())
->setTimestamp(
mktime($hour, $minute,$second, $month, $day, $year)
);
var_dump($datetime);
只是一个明显的注意事项:
请记住DateTimeImmutable对象是不可变的:),因此每个方法setSomething
都返回一个DateTimeImmutable的新实例,并且它不会更改初始实例。
所以
$timestamp = 12345;
$datetime = new DateTimeImmutable();
$datetime->setTimestamp($timestamp); // wrong
$datetime = $datetime->setTimestamp($timestamp); // right
// or better
$datetime = (new DateTimeImmutable())->setTimestamp($timestamp);