PHP DateTime可以将日期和时间组合在一起。
P粉178894235
P粉178894235 2023-07-31 10:43:08
[PHP讨论组]
<p>如何在PHP中使用MySQL的'time'列格式将日期和时间组合在一起?</p> <pre class="brush:php;toolbar:false;">$date = New DateTime(); $time = $record-&gt;time //14:00:00</pre> <p>这样做</p> <pre class="brush:php;toolbar:false;">$date = New DateTime(); $date-&gt;setTime(explode(':',$record-&gt;time)[0],explode(':',$record-&gt;time)[1],explode(':',$record-&gt;time)[2]);</pre> <p>有7没有更好的方法</p>
P粉178894235
P粉178894235

全部回复(1)
P粉530519234

我个人更喜欢使用高级对象而不仅仅是数组或字符串,所以这是我处理的方式。对于有些人来说,这可能有些过度,我完全理解,不过核心方法也可以很容易地重写为全局函数,希望这一点可以考虑到。

我认为整体上非常简单明了,几乎与您的代码完全相同,只是在分割后我们将其转换为整数,然后验证小时是否在预期范围内。

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);
    }
}

用法:

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"
}

Demo: https://3v4l.org/B6mr4#v8.2.7

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号