1

I'm trying to add four hours to a date but the resultant time is incorrect

$date = $dates[0] < $dates[1] ? $dates[1] : $dates[0];
$new_date = date("Y-m-d H:i:s", strtotime('+4 hours', $date));
echo $date;
echo "<br/>". $new_date;

The result i'm getting is

2015-09-17 09:36:18

1969-12-31 20:33:35

The first date is correct but the second isn't, it should be 4 hours ahead of the first

Community
  • 1
  • 1
Ceri Turner
  • 830
  • 2
  • 12
  • 36

4 Answers4

4

Does this work?

$date = $dates[0] < $dates[1] ? $dates[1] : $dates[0];
$new_date = date("Y-m-d H:i:s", strtotime('+4 hours', strtotime($date)));
echo $date;
echo "<br/>". $new_date;
  

You were passing $date AS the second argument of strtotime, and it's not a UNIX timestamp (as you said). So with strtotime again, you should convert it in a UNIX timestamp, and then pass it to strtotime.


Progrower
  • 363
  • 5
  • 18
Zerquix18
  • 769
  • 6
  • 19
2

Add timestamps to a timestamp, not to a date string.

echo  date("Y-m-d H:i:s", strtotime('+4 hours', strtotime("2015-09-17  09:36:18")));
                                                ^

Fiddle

That is the right syntax. You can simplify it however with

echo  date("Y-m-d H:i:s", strtotime('2015-09-17 09:36:18 +4 hours'));

Fiddle

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
2

You're using strtotime incorrectly. Its second argument MUSt be a unix timestamp:

php > var_dump(strtotime('+4 hours', 12345));
int(26745)
php > var_dump(strtotime('+4 hours', '2015-09-17 09:36:18'));
PHP Notice:  A non well formed numeric value encountered in php shell code on line 1
int(16415)

Your call should be

php >  var_dump(date('r', strtotime('2015-09-17 09:36:18 + 4 hours')));
                                                        ^^^^^^^^^^^
string(31) "Thu, 17 Sep 2015 13:36:18 -0500"
php >
Marc B
  • 356,200
  • 43
  • 426
  • 500
2

Both other answers are correct.

Not seeing what you have in your $dates array makes it a bit tricky to give exact answer :) but in the following example i assumed you have a well formatted string date, in which case you need to convert it back to the timestamp using same method (strtotime) before adding what you like into it .

$date = (new DateTime('now'))->format('Y-m-d H:i:s');
$new_date = date('Y-m-d H:i:s', strtotime('+4 hours', strtotime($date)));

echo $date . PHP_EOL . $new_date;

In other word, if your $date array contains UNIX time stamp then your original code should work

$date = (new DateTime('now'))->getTimestamp();
$new_date = date("Y-m-d H:i:s", strtotime('+4 hours', $date));
Ali
  • 2,993
  • 3
  • 19
  • 42