国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

PHP DateTime可以將日期和時間組合在一起。
P粉178894235
P粉178894235 2023-07-31 10:43:08
0
1
674
<p>如何在PHP中使用MySQL的'time'列格式將日期和時間組合在一起?</p> <pre class="brush:php;toolbar:false;">$date = New DateTime(); $time = $record->time //14:00:00</pre> <p>這樣做</p> <pre class="brush:php;toolbar:false;">$date = New DateTime(); $date->setTime(explode(':',$record->time)[0],explode(':',$record->time)[1],explode(':',$record->time)[2]);</pre> <p>有7沒有更好的方法</p>
P粉178894235
P粉178894235

全部回復(1)
P粉530519234

我個人更喜歡使用高級對象而不僅僅是數(shù)組或字符串,所以這是我處理的方式。對于有些人來說,這可能有些過度,我完全理解,不過核心方法也可以很容易地重寫為全局函數(shù),希望這一點可以考慮到。

我認為整體上非常簡單明了,幾乎與您的代碼完全相同,只是在分割后我們將其轉(zhuǎn)換為整數(shù),然后驗證小時是否在預期范圍內(nèi)。

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

最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板