John
John

Reputation: 4944

Create Variable in PHP Equal to Current Time Minus One Hour

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

Upvotes: 20

Views: 53295

Answers (8)

Avinash Borse
Avinash Borse

Reputation: 369

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

Upvotes: 5

JamLizzy101
JamLizzy101

Reputation: 165

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

Upvotes: 2

Jason McCreary
Jason McCreary

Reputation: 73031

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

$hour_ago = strtotime('-1 hour');

Upvotes: 44

kaleazy
kaleazy

Reputation: 6242

First convert hours into seconds (3600) then use the following:

$your_date = date('F jS, Y',time() - 3600);

Upvotes: -1

Nemoden
Nemoden

Reputation: 9056

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

See time PHP function for more information.

Upvotes: 12

Tadeck
Tadeck

Reputation: 137440

Current time is equal to time() (current time given in seconds after Unix epoch).

Thus, to calculate what you need, you need to perform calculation: time() - 60*60 (current time in seconds minus 60 minutes times 60 seconds).

$time_you_need = time() - 60*60;

Upvotes: -1

pkavanagh
pkavanagh

Reputation: 1046

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

Upvotes: 26

MitMaro
MitMaro

Reputation: 5937

Assuming that a timestamp is fine you can use the time function like so

<?php
$livetime = time() - 60 * 60;

Upvotes: -1

Related Questions