PHP - Strtotime - Add hours
Asked Answered
P

8

14

I have this variable:

$timestamp = strftime("%Y-%m-%d %h:%M:%S %a", time ());

I simply want to add three hours and echo it out.

I have seen the way where you can do the 60 * 60 * 3 method or the hard code "+ 3 hours" where it understands the words.

What is the best way of getting this result?

Paterson answered 18/6, 2012 at 2:26 Comment(0)
T
8
$timestamp = strftime("%Y-%m-%d %h:%M:%S %a", time() + 3*60*60)

3*60*60 is the best way

Tangy answered 18/6, 2012 at 2:30 Comment(0)
E
20

The best way is what you think is more readable. The following expressions are identical:

time() + 3 * 60 * 60

strtotime('+3 hours')
Eyehole answered 18/6, 2012 at 2:37 Comment(0)
L
12

i always do like this

$current_time = date('Y-m-d H:i:s');
$new_time = strtotime($current_time . "+3hours");
echo $new_time;

or

$new_time = mktime(date('H')+3, 0, 0, date('m'), date('d'), date('Y'));
$new_time = date('Y-m-d H:i:s', $new_time);
echo $new_time;
Lesalesak answered 18/6, 2012 at 4:8 Comment(0)
T
8
$timestamp = strftime("%Y-%m-%d %h:%M:%S %a", time() + 3*60*60)

3*60*60 is the best way

Tangy answered 18/6, 2012 at 2:30 Comment(0)
M
2

Just add seconds to add hours:

strtotime($your_date)+2*60*60 

This will add two hours in your date.

Moneymaker answered 29/1, 2016 at 17:7 Comment(0)
L
1

You can use DateTime::modify to add time, but I would just do time()+10800.

Llanes answered 18/6, 2012 at 2:31 Comment(0)
D
1
$time = new DateTime("+ 3 hour");
$timestamp = $time->format('Y-M-d h:i:s a');

Clear and concise :)

Dragon answered 18/6, 2012 at 2:37 Comment(0)
T
0

If you want to go 'modern':

$d = new DateTime();
$d->add(new DateInterVal('P3H'));
$timestamp = $d->format('Y-M-d h:i:s a');

refs: DateTime object

Taken answered 18/6, 2012 at 2:32 Comment(1)
That would be DateInterval('PT3H'), IMHO,Lyle
S
0

$currentTime = time(); // Get the current timestamp

$newTime = $currentTime + 3 * 60; // Add 3 minutes (3 * 60 seconds) to the current timestamp

$formattedTime = date('Y-m-d H:i:s', $newTime); echo $formattedTime;

Signpost answered 19/12, 2023 at 10:13 Comment(1)
Hi, and welcome, normally it is a good practices to share a bit of text / explanation additional to your code.Acceptor

© 2022 - 2024 — McMap. All rights reserved.