PHP DateTime合并日期和时间

huangapple go评论120阅读模式
英文:

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(&#39;intval&#39;, explode(&#39;:&#39;, $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&#39;t
        // need to check those.
        // The seconds could include decimals, however for this purpose we are ignoring them.
        if ($hours &gt; 23 || $hours &lt; 0) {
            throw new InvalidArgumentException(&#39;Hours must be between 0 and 23&#39;);
        }

        return new self($hours, $minutes, $seconds);
    }

    public function toDateTime(DateTimeInterface $dateTime = null) : DateTimeInterface
    {
        $dateTime ??= new DateTimeImmutable();

        return $dateTime-&gt;setTime($this-&gt;hours, $this-&gt;minutes, $this-&gt;seconds);
    }
}

Usage:

var_dump(MySqlTime::fromMySqlTimeAsDurationInDay(&#39;12:34:56&#39;)-&gt;toDateTime());

Output:

object(DateTimeImmutable)#3 (3) {
  [&quot;date&quot;]=&gt;
  string(26) &quot;2023-07-31 12:34:56.000000&quot;
  [&quot;timezone_type&quot;]=&gt;
  int(3)
  [&quot;timezone&quot;]=&gt;
  string(16) &quot;Europe/Amsterdam&quot;
}

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

huangapple
  • 本文由 发表于 2023年7月31日 23:55:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76805259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定