Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Merge two date objects into one

Tags:

date

php

datetime

I've got two date objects sent from a date input and a time input.

I want to generate a DateTime object with the yyyy-mm-dd from the date input and hh-mm from the time input.

Data sent from date input

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

Data sent from time input

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

I need to merge these two dates into:

2015-08-04 02:02

I've been playing around with exploding the string, etc to no avail,

Any help would be appriciated

Cheers

like image 604
Lee Brindley Avatar asked Aug 28 '15 10:08

Lee Brindley


1 Answers

You can create two DateTime objects from your strings, then use the second to set the time on the first.

$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');

Here's an eval.in with an example - https://eval.in/424209

like image 130
Styphon Avatar answered Nov 20 '22 12:11

Styphon