[英]Add hours to datetime in PHP
I got a variable named $transactiontime
. 我有一个名为
$transactiontime
的变量。 I want to add 6 hours to that variable. 我想为该变量添加6个小时。 But I need to exclude the time between 12.00AM and 6.00AM.
但我需要排除上午12点到早上6点之间的时间。
For example, I made a transaction at 1/1/2016 11.00PM
. 例如,我在
1/1/2016 11.00PM
日1/1/2016 11.00PM
进行了交易。 After adding 6 hours, the output should be 2/1/2016 11.00AM
. 添加6小时后,输出应为
2/1/2016 11.00AM
。
How do I do this? 我该怎么做呢? Thank you
谢谢
DateTime
is an awesome feature in PHP DateTime
是PHP中的一个很棒的功能
$string = '1/1/2016 11.00PM';
$date = new DateTime($string);
$interval = new DateInterval('PT6H');
$date->add($interval);
// Now add another 6 hours while we are between 12:00 AM and 6:00 AM
while($date->format('G') >= 0 && $date->format('G') <= 6)
{
$date->add($interval);
}
echo $date->format('H:i:s M-j-Y');
This outputs the desired 这输出所需的
11:00:00 Jan-2-2016
Update 更新
After our extensive discussion in chat about the logic of this particular piece of code, we came to the conclusion, that any transaction done between midnight and 6:00 AM should add 6 hours starting from 6:00 AM (so, basically, set it to midday ). 在我们在讨论这段特定代码的逻辑的广泛讨论之后,我们得出结论,在午夜和早上6点之间完成的任何交易应该从早上 6点开始增加6小时(所以,基本上,设置它到中午 )。
And every other transaction adds 6 hours normally. 每个其他交易通常会增加6个小时。 But if after adding those 6 hours the time interval falls between midnight and 6:00 AM , only the respective amount of time between the initial and midnight and the rest should be added to 6:00 AM , which is, basically is adding just 12 hours to the initial value.
但是如果在加上那6个小时之后,时间间隔在午夜和早上6点之间,那么只有初始和午夜之间的相应时间量和其余时间应该加到早上6点 ,这基本上只是增加了12个小时到初始值。
So here's the modified code: 所以这是修改后的代码:
$date = new DateTime($string);
$interval = new DateInterval('PT6H');
if($date->format('G') >= 0 && $date->format('G') <= 6)
{
$date->setTime(12,0,0);
}
else
{
$date->add($interval);
if($date->format('G') >= 0 && $date->format('G') <= 6)
{
$date->add($interval);
}
}
echo $date->format('H:i:s M-j-Y');
Example #1 示例#1
// input
$string = '1/1/2016 3.00AM';
//output
12:00:00 Jan-1-2016 // this is midday
Example #2 例#2
// input
$string = '1/1/2016 11.00AM';
//output
17:00:00 Jan-1-2016 // this is 5:00 PM
Example #3 例#3
// input
$string = '1/1/2016 11.00PM';
//output
11:00:00 Jan-2-2016 // this is 11:00 AM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.