Merge Date & Time

42,981

Solution 1

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 $time into a timestamp.

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"));
                                            ^           ^

Solution 2

And for those coming here working with DateTime objects:

$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'
Share:
42,981

Related videos on Youtube

CodeGuru
Author by

CodeGuru

Startups , Startups & Startups. Failure , Failure & Failure. I'm not giving up.

Updated on July 17, 2022

Comments

  • CodeGuru
    CodeGuru almost 2 years
    $combinedDT = date('Y-m-d H:i:s', strtotime('$date $time'));
    

    Date Format 2013-10-14

    time format 23:40:19

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

  • Jarek Kowol
    Jarek Kowol about 4 years
    Solution 2 is only proper. First solutions may cause a lot of problems ;)
  • Wilbo Baggins
    Wilbo Baggins about 4 years
    @JarekKowol could you explain a bit? What problems are you referring to?
  • bmatovu
    bmatovu about 3 years
    The second solution preserves the TimeZone