英文:
PHP DateTime combine a date and time
问题
在PHP中,如何将日期和时间与MySQL 'time'列格式组合在一起:
$date = new DateTime();
$time = $record->time; // 14:00:00
// 我可以这样做
$date = new DateTime();
$date->setTime(explode(':', $record->time)[0], explode(':', $record->time)[1], explode(':', $record->time)[2]);
// 是否有更好的方法?
如果您想要更好的方法,请尝试以下代码:
$date = new DateTime($record->time);
这个方法将时间字符串直接传递给DateTime
构造函数,它会自动解析并设置日期和时间。这是更简洁的方法来组合日期和时间。
英文:
How do I combine a Date & Time in PHP using a mysql 'time' column format
$date = New DateTime();
$time = $record->time //14:00:00
I can do this
$date = New DateTime();
$date->setTime(explode(':',$record->time)[0],explode(':',$record->time)[1],explode(':',$record->time)[2]);
Is there a 'better' way
答案1
得分: 1
以下是您要翻译的内容:
我个人喜欢使用更高级别的对象而不仅仅是数组或字符串进行工作,所以这里是我处理这个问题的方式。对于一些人来说,这可能是过于复杂了,我完全理解,不过核心方法可以很容易地重写为全局函数,所以希望可以考虑到这一点。
我认为这总体上相当简单,几乎与您的代码完全相同,只是在分解后我们将其转换为int
,然后验证小时是否在预期范围内。
readonly class MySqlTime
{
public function __construct(
public int $hours,
public int $minutes,
public int $seconds,
) {
}
public static function fromMySqlTimeAsDurationInDay(string $time): self
{
[$hours, $minutes, $seconds] = array_map('intval', explode(':', $time));
// 确保只有正值在一天内。
// MySql应该已经抛出了关于分钟或秒超出范围的错误,所以我们不需要检查这些。
// 秒可能包括小数部分,但是为了这个目的,我们忽略了它们。
if ($hours > 23 || $hours < 0) {
throw new InvalidArgumentException('Hours must be between 0 and 23');
}
return new self($hours, $minutes, $seconds);
}
public function toDateTime(DateTimeInterface $dateTime = null) : DateTimeInterface
{
$dateTime ??= new DateTimeImmutable();
return $dateTime->setTime($this->hours, $this->minutes, $this->seconds);
}
}
用法:
var_dump(MySqlTime::fromMySqlTimeAsDurationInDay('12:34:56')->toDateTime());
输出:
object(DateTimeImmutable)#3 (3) {
["date"]=>
string(26) "2023-07-31 12:34:56.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
演示:https://3v4l.org/B6mr4#v8.2.7
英文:
I personally like working with higher level objects instead of just arrays or strings, so here's how I would tackle this. For some people, this is majorly overkill, and I totally get that, however the core method can easily be just rewritten as a global function, too, so hopefully that can be taken into account.
I think it is overall pretty straight-forward, and almost identical to your code except after exploding we convert to int
and then validate that the hours are in an expected range.
readonly class MySqlTime
{
public function __construct(
public int $hours,
public int $minutes,
public int $seconds,
) {
}
public static function fromMySqlTimeAsDurationInDay(string $time): self
{
[$hours, $minutes, $seconds] = array_map('intval', explode(':', $time));
// Ensure only positive values on a single day.
// MySql should already be throwing errors about minutes or seconds being out of range, so we don't
// need to check those.
// The seconds could include decimals, however for this purpose we are ignoring them.
if ($hours > 23 || $hours < 0) {
throw new InvalidArgumentException('Hours must be between 0 and 23');
}
return new self($hours, $minutes, $seconds);
}
public function toDateTime(DateTimeInterface $dateTime = null) : DateTimeInterface
{
$dateTime ??= new DateTimeImmutable();
return $dateTime->setTime($this->hours, $this->minutes, $this->seconds);
}
}
Usage:
var_dump(MySqlTime::fromMySqlTimeAsDurationInDay('12:34:56')->toDateTime());
Output:
object(DateTimeImmutable)#3 (3) {
["date"]=>
string(26) "2023-07-31 12:34:56.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论