php 合并日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19375184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:22:14  来源:igfitidea点击:

Merge Date & Time

phphtmldatedatetimetime

提问by CodeGuru

$combinedDT = date('Y-m-d H:i:s', strtotime('$date $time'));

Date Format 2013-10-14

日期格式 2013-10-14

time format 23:40:19

时间格式 23:40:19

i'm getting zeros when trying to store into a datetime datatype

尝试存储到日期时间数据类型时我得到零

回答by Amal Murali

You're currently doing strtotime('$date $time'). Variables wrapped in single-quotes aren't interpolated. If you use single-quotes, PHP will treat it as a literal string, and strototime()will try to convert the string $date $timeinto a timestamp.

你目前正在做strtotime('$date $time'). 用单引号括起来的变量没有内插。如果使用单引号,PHP 会将其视为文字字符串,并strototime()尝试将字符串$date $time转换为时间戳。

It'll fail and that would explain why you're getting incorrect results.

它会失败,这将解释为什么你得到不正确的结果。

You need to use double quotes instead:

您需要改用双引号:

$combinedDT = date('Y-m-d H:i:s', strtotime("$date $time"));
                                            ^           ^

回答by Wilbo Baggins

And for those coming here working with DateTime objects:

对于那些来这里使用 DateTime 对象的人:

$date = new DateTime('2017-03-14');
$time = new DateTime('13:37:42');

// Solution 1, merge objects to new object:
$merge = new DateTime($date->format('Y-m-d') .' ' .$time->format('H:i:s'));
echo $merge->format('Y-m-d H:i:s'); // Outputs '2017-03-14 13:37:42'

// Solution 2, update date object with time object:
$date->setTime($time->format('H'), $time->format('i'), $time->format('s'));
echo $date->format('Y-m-d H:i:s'); // Outputs '2017-03-14 13:37:42'