Add 'x' amount of hours to date

2019-01-04 03:09发布

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

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

What id like to do is have a new variable $new_time equal $now + $hours. $hours being an amount of hours ranging anywhere from 24-800.

Any suggestions?

10条回答
欢心
2楼-- · 2019-01-04 03:17

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.

查看更多
来,给爷笑一个
3楼-- · 2019-01-04 03:18

You can use strtotime() to achieve this:

$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours
查看更多
何必那么认真
4楼-- · 2019-01-04 03:23

You may use something like the strtotime() function to add something to the current timestamp. $new_time = date("Y-m-d H:i:s", strtotime('+5 hours')).

If you need variables in the function, you must use double quotes then like strtotime("+{$hours} hours"), however better you use strtotime(sprintf("+%d hours", $hours)) then.

查看更多
小情绪 Triste *
5楼-- · 2019-01-04 03:24

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";
查看更多
狗以群分
6楼-- · 2019-01-04 03:27

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
查看更多
甜甜的少女心
7楼-- · 2019-01-04 03:27
$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.

查看更多
登录 后发表回答