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


PHP: Merge two date objects into one

我已经从日期输入和时间输入发送了两个日期对象。

我想生成一个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

我一直在玩爆炸字符串,等无济于事,

任何帮助将不胜感激

欢呼

您可以从您的字符串创建两个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。在一个例子- https://eval.in/424209

你可以像这样分割"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);

试试这个,

$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];
$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;

这样应该可以。

$finalDateD仅为年、月和日创建日期字符串和$finalDateT仅为小时、分钟创建日期字符串然后将其连接到变量$finalDate;

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