[php] Add 'x' number of hours to date

I currently have php returning the current date/time like so:

$now = date("Y-m-d H:m:s");

What I'd like to do is have a new variable $new_time equal $now + $hours, where $hours is a number of hours ranging from 24 to 800.

Any suggestions?

This question is related to php date datetime dateadd hour

The answer is


You can try lib Ouzo goodies, and do this in fluent way:

echo Clock::now()->plusHours($hours)->format("Y-m-d H:m:s");

API's allow multiple operations.


For a given DateTime, you can add days, hours, minutes, etc. Here's some examples:

$now = new \DateTime();

$now->add(new DateInterval('PT24H')); // adds 24 hours

$now->add(new DateInterval('P2D')); // adds 2 days

PHP: DateTime::add - Manual https://www.php.net/manual/fr/datetime.add.php


I use following function to convert normal date-time value to mysql datetime format.

private function ampmtosql($ampmdate) {
            if($ampmdate == '')
                return '';
            $ampm = substr(trim(($ampmdate)), -2);
            $datetimesql = substr(trim(($ampmdate)), 0, -3);
            if ($ampm == 'pm') {
                $hours = substr(trim($datetimesql), -5, 2);
                if($hours != '12')
                    $datetimesql = date('Y-m-d H:i',strtotime('+12 hour',strtotime($datetimesql)));
            }
            elseif ($ampm == 'am') {
                $hours = substr(trim($datetimesql), -5, 2);
                if($hours == '12')
                    $datetimesql = date('Y-m-d H:i',strtotime('-12 hour',strtotime($datetimesql)));
            }
            return $datetimesql;
        }

It converts datetime values like,

2015-06-04 09:55 AM -> 2015-06-04 09:55
2015-06-04 03:55 PM -> 2015-06-04 15:55
2015-06-04 12:30 AM -> 2015-06-04 00:55

Hope this will help someone.


I like those built-in php date expressions like +1 hour, but for some reason, they fall out of my head all of the time. Besides, none of the IDEs I'm aware of suggest auto-completion facility for that kind of stuff. And, finally, although juggling with those strtotime and date functions is no rocket science, I have to google their usage each time I need them.

That's why I like the solution that eliminates (at least mitigates) those issues. Here's how adding x hours to a date can look like:

(new Future(
    new DateTimeFromISO8601String('2014-11-21T06:04:31.321987+00:00'),
    new NHours($x)
))
    ->value();

As a nice bonus, you don't have to worry about formatting the resulting value, it's already is ISO8601 format.

This example uses meringue library, you can check out more examples here.


for add 2 hours to "now"

$date = new DateTime('now +2 hours');

or

$date = date("Y-m-d H:i:s", strtotime('+2 hours', $now)); // as above in example

or

$now = new DateTime();

$now->add(new DateInterval('PT2H')); // as above in example

You can use strtotime() to achieve this:

$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours

You can also use the unix style time to calculate:

$newtime = time() + ($hours * 60 * 60); // hours; 60 mins; 60secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $newtime) ."\n";

An other solution (object-oriented) is to use DateTime::add

Example:

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

PHP documentation.


   $now = date("Y-m-d H:i:s");
   date("Y-m-d H:i:s", strtotime("+1 hours $now"));

Correct

You can use strtotime() to achieve this:

$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', strtotime($now))); // $now + 3 hours

Um... your minutes should be corrected... 'i' is for minutes. Not months. :) (I had the same problem for something too.

$now = date("Y-m-d H:i:s");
$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours

I use this , its working cool.

//set timezone
date_default_timezone_set('GMT');

//set an date and time to work with
$start = '2014-06-01 14:00:00';

//display the converted time
echo date('Y-m-d H:i',strtotime('+1 hour +20 minutes',strtotime($start)));

$date_to_be-added="2018-04-11 10:04:46";
$added_date=date("Y-m-d H:i:s",strtotime('+24 hours', strtotime($date_to_be)));

A combination of date() and strtotime() functions will do the trick.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to dateadd

How to add days to the current date? How to select last one week data from today's date Add 'x' number of hours to date MySQL - DATE_ADD month interval Subtract minute from DateTime in SQL Server 2005 SQL Server 2005 Using DateAdd to add a day to a date

Examples related to hour

Add 'x' number of hours to date Java getHours(), getMinutes() and getSeconds() How do I get hour and minutes from NSDate? Extracting hours from a DateTime (SQL Server 2005)