Add ‘x’ amount of hours to date

Add ‘x’ amount of hours to date

Asked on December 27, 2018 in PHP.
Add Comment


  • 3 Answer(s)

    The strtotime() function can be used to add anything to the current timestamp.

    $new_time = date("Y-m-d H:i:s", strtotime('+5 hours')).
    
    

    If variables are needed use double quotes then do like this, strtotime(“+{$hours} hours”),  or strtotime(sprintf(“+%d hours”, $hours)) then.

    Answered on December 27, 2018.
    Add Comment

    The solution for the above question is try to use DateTime::add function.

    Example:

    $now = new DateTime(); //current date/time
    $now->add(new DateInterval("PT{$hours}H"));
    $new_time = $now->format('Y-m-d H:i:s');
    

    The link for php documentation..

    Answered on December 27, 2018.
    Add Comment

    One can solve this question by using strtotime() function.

    $new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours
    
    
    Answered on December 27, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.