Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Variable in PHP Equal to Current Time Minus One Hour

Tags:

php

In PHP, how could I create a variable called $livetime that equals the current time minus 1 hour?

like image 670
John Avatar asked May 19 '11 01:05

John


People also ask

Can you subtract dates in PHP?

The date_sub() function subtracts some days, months, years, hours, minutes, and seconds from a date.

How can I get first day of current month in PHP?

php $dt = "2008-02-23"; echo 'First day : '. date("Y-m-01", strtotime($dt)).

How can I change current date in PHP?

PHP doesn't have a date and time on its own. time() returns the current timestamp of the server's time. Depending on your operating system, it may well be that you (i.e. the user that runs your script's process) are actually not allowed to change the server date and time.


5 Answers

Another way - without all the math and, in my opinion, reads better.

$hour_ago = strtotime('-1 hour');
like image 146
Jason McCreary Avatar answered Sep 28 '22 12:09

Jason McCreary


If you're looking for how to display the time in a human readable format, these examples will help:

$livetime = date('H:i:s', time() - 3600); // 16:00:00
$livetime = date('g:iA ', time() - 3600); // 4:00PM
like image 41
pkavanagh Avatar answered Sep 28 '22 14:09

pkavanagh


$livetime = time() - 3600; // 3600 seconds in 1 hour : 60 seconds (1 min) * 60 (minutes in hour)

See time PHP function for more information.

like image 31
Nemoden Avatar answered Sep 28 '22 14:09

Nemoden


convert your date to strtotime and then subtract one hour from it

$now =  date('Y-m-d H:i:s');
$time   = strtotime($now);
$time   = $time - (60*60); //one hour
$beforeOneHour = date("Y-m-d H:i:s", $time);
like image 23
Avinash Borse Avatar answered Sep 28 '22 14:09

Avinash Borse


You could use the date_create function along with the date_sub function like I have shown here below: -

$currentTime = date_create(now());
$modifyTime = date_sub($currentTime,date_interval_create_from_date_string("1 hour"));
$liveTime = $modifyTime->format('Y-m-d H:i:s');
like image 44
JamLizzy101 Avatar answered Sep 28 '22 14:09

JamLizzy101