skip to Main Content

I am trying to add the time to the date but I am having trouble with the correct code to do it.

$dateToday = date('Y-m-d');
$timeToAddToDate = 2:52; // This is from user input so it is not always 2:52 am o'clock, sometimes 21:30 o'clock depending on the user input;

I tried

$s = new DateTime($date_now);
$t = $s->modify('+{$timeToAddToDate} seconds');

$results = date('Y-m-d H:i:s',$t); // this is not working`

echo $results;`

I am expecting the results to be "2024-07-28 2:52" or "{date today} {time input by user}".

I want the results then converted to timestamp and save it to the database column with a timestamp type.

So after the $results, I will convert it to strtotime($results) then insert it via sql query to the database.

2

Answers


  1. For this you can use strtotime:

    $dateToday = date("Y-m-d"); $resultTimestamp = strtotime($today . " ". $timeToAddToDate); $resultDate = date("Y-m-d H:i", $resultTimestamp);

    Login or Signup to reply.
  2. This is a way to go (you can compact the code, I probably overdetailed it.)

    <?php
    
    $currentDate = new DateTime();
    $inputTime = '2:52'; // 2:52 without the quotes is syntax error
    
    /*
    Extract hours and minutes from the input string 
    (you should also make sure you'll always receive your string with this format, never trust user input).
    */
    $inputTime = explode(':', $inputTime);
    $hours = $inputTime[0];
    $minutes = $inputTime[1];
    
    // Format response to string (or keep it as a DateTime object by removing the format method
    $response = $currentDate->setTime($hours, $minutes)->format('Y-m-d H:i');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search