添加的时间至今的“X”号

问题描述 投票:57回答:11

我现在有PHP返回像这样的当前日期/时间:

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

我希望做的是有一个新的变量$new_time等于$now + $hours,其中$hours是数个小时,从24到800。

有什么建议么?

php datetime date dateadd
11个回答
100
投票

您可以使用类似strtotime()功能的东西添加到当前时间戳。 $new_time = date("Y-m-d H:i:s", strtotime('+5 hours'))

如果您需要在函数的变量,你必须用双引号然后像strtotime("+{$hours} hours"),但更好的使用strtotime(sprintf("+%d hours", $hours))然后。


0
投票
$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)));

date()strtotime()功能的组合,会做的伎俩。


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

34
投票

的其它溶液(面向对象)是使用的DateTime ::添加

例:

$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


18
投票

您可以使用strtotime()来实现这一目标:

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

9
投票

正确

您可以使用的strtotime()来实现这一目标:

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

5
投票

嗯......你分钟应予以纠正......“我”是分钟。而不是几个月。 :)(我有一些同样的问题了。

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

4
投票

您也可以使用UNIX风格的时间来计算:

$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";

2
投票

您可以尝试的lib Ouzo goodies,并用流利的方式做到这一点:

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

API的允许多个操作。


1
投票

我用这个,它的工作凉爽。

//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)));

0
投票

我用下面的函数转换成正常的日期时间值到mysql日期时间格式。

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;
        }

它可以转换日期时间值一样,

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

希望这会帮助别人。

© www.soinside.com 2019 - 2024. All rights reserved.