开发者

5 Different Times in PHP

开发者 https://www.devze.com 2023-02-02 18:19 出处:网络
I need to 开发者_开发问答have 5 vars like this: $time1 = \"The time now -5 minutes\"; $time2 = \"The time now -10 minutes\";

I need to 开发者_开发问答have 5 vars like this:

$time1 = "The time now -5 minutes";
$time2 = "The time now -10 minutes";
$time3 = "The time now -20 minutes";
$time4 = "The time now -30 minutes";
$time5 = "The time now -40 minutes";

So assuming it's 9 AM, $time1 should be "8:55 AM"

It would be so great if anyone could help me out with this :)

Thanks in advance for every hint,

Camillo


Use strtotime() and then date() to format it however you want,

$time1 = date("g:i A", strtotime("-5 mins")); // e.g. 8:55 AM
$time2 = date("g:i A", strtotime("-10 mins")); // e.g. 8:50 AM
// ...etc


$time  = date('g:i A');
$time1 = date('g:i A', strtotime($time) -5 *60);

and so on..


$dt = new DateTime();
$interval = new DateInterval('PT5M');
for ($i = 0; $i < 5; ++$i)
{
  $dt->sub($interval);
  echo "The time is now ".$dt->format('g:i A')."\n";
}

Gives:

The time is now 5:00 PM
The time is now 4:55 PM
The time is now 4:50 PM
The time is now 4:45 PM
The time is now 4:40 PM

Now this is every 5 minutes, but just adjust the PT5M to PT10M, etc.


The nicest way to do time manipulation, presuming you have at least PHP 5.3, is to use the new DateTime functionality:

$time1 = new DateTime('-5 minutes');
$time2 = new DateTime('-10 minutes');

etc. You can then use all the functions listed in the manual: PHP: Date/Time.

0

精彩评论

暂无评论...
验证码 换一张
取 消