PHP DateTime can combine date and time.
P粉178894235
2023-07-31 10:43:08
<p>How to combine date and time together using MySQL's 'time' column format in PHP? </p>
<pre class="brush:php;toolbar:false;">$date = New DateTime();
$time = $record->time //14:00:00</pre>
<p>Do this</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>There is no better way</p>
I personally prefer to use high-level objects instead of just arrays or strings, so this is how I approach it. This may be overkill for some, which I totally understand, but the core methods can also be easily rewritten as global functions, so hopefully this can be taken into account.
I think overall it's very simple and straightforward, almost identical to your code, except after splitting we convert it to an integer and then verify that the hour is within the expected range.
usage:
Output:
Demo: https://3v4l.org/B6mr4#v8.2.7