PHP:将两个日期对象合并为一个

4

我收到了两个日期对象,分别来自日期输入和时间输入。

我想要生成一个 DateTime 对象,其中包含来自日期输入的 yyyy-mm-dd 和来自时间输入的 hh-mm。

从日期输入发送的数据:

[search_from_date] => 2015-08-04T23:00:00.000Z

从时间输入发送的数据

 [search_from_time] => 1970-01-01T02:02:00.000Z

我需要将这两个日期合并为:
2015-08-04 02:02

我一直在尝试将字符串进行拆分,但是没有成功,希望能得到帮助。谢谢。
5个回答

5
你可以从你的字符串中创建两个DateTime对象,然后使用第二个DateTime对象来设置第一个DateTime对象的时间。
$arr = ['search_from_date' => '2015-08-04T23:00:00.000Z', 'search_from_time' => '1970-01-01T02:02:00.000Z'];
$date = new DateTime($arr['search_from_date']);
$time = new DateTime($arr['search_from_time']);
$date->setTime($time->format('H'), $time->format('i'), $time->format('s'));
echo $date->format('r');

这是一个带有示例的 eval.in 链接 - https://eval.in/424209

啊,太棒了,是的,这看起来正确。我很快会测试并接受。谢谢! - Lee Brindley

0

类似这样的代码应该可以工作。

$finalDateD 创建一个只包含年、月和日的日期字符串, 而$finalDateT则创建一个只包含小时和分钟的日期字符串。 然后将它们连接到变量$finalDate中;

$finalDateD = date('Y-m-d', strtotime($search_from_date));
$finalDateT = date('H:i', strtotime($search_from_time));
$finalDate = $finalDateD.' '.$finalDateT;

0

你可以这样按照“T”进行分割:

$search_from_date = "2015-08-04T23:00:00.000Z";
$search_from_time = "1970-01-01T02:02:00.000Z";

$tab_date = explode("T", $search_from_date);
$tab_time = explode("T", $search_from_time);

$date_time = new DateTime("$tab_date[0]T$tab_time[1]");

var_dump($date_time);

0

请尝试这个:

$search_from_date = '2015-08-04T23:00:00.000Z';
$search_from_time = '1970-01-01T02:02:00.000Z';

$data = explode('T',$search_from_date);
$data1 = explode('T',$search_from_time);
$data1 = explode('.',$data1[1]);

echo $data[0].' '.$data1[0];

0
$time=new DateTime('1970-01-01T02:02:00.000Z');
$date=new DateTime('2015-08-04T23:00:00.000Z');
$newDateTime= new DateTime();
$newDateTime->setTime($time->format('H'),$time->format('i'),$time->format('s'));
$newDateTime->setDate($date->format('Y'),$date->format('m'),$date->format('d')); 
echo $newDateTime->format('Y/m/d H:i'));
exit;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接