0

I have put together some code that adds an amount of days on to a date/time. For some reason the first day is calculated as 12 hours. For example, if I set one day it will add 12 hours. If I set 2 days it will add 36 hours.

$postdate = "03/08/2014 14:55:18";

 echo $postdate;


//SPLIT UP DATE
$month = substr("$postdate", 0, -17);
$day = substr("$postdate", 3, -14);
$year = substr("$postdate", 6, -9);
$hour = substr("$postdate", 11, -6);
$min = substr("$postdate", 14, -3);
$sec = substr("$postdate", 17);




//DAYS LEFT
$days_left = 1; // Set Days Left
$add_day = "P$days_left D";
$tot_day = preg_replace('/\s+/', '', $add_day); // Trims white space

// Add days
$date = new DateTime();
$date->setDate($year, $month, $day);
$date->setTime($hour, $min, $sec);
$date->add(new DateInterval("$tot_day"));
$end = $date->format("m/d/y h:m:i");

// If time is up
if (time(new DateTimeZone('Europe/London')) > strtotime("$end"))
{
// Times Up
}

else

{
// Time Left
}

?>

Here I have the told the code to add 1 day to the date and time. But my result adds 12 hours instead.

Any help is appreciated. Thanks.

Chris 'Pig' Hill
  • 175
  • 2
  • 12
  • 1
    you might find it a lot easier to utilize the `strtotime` php function. Once you convert the date string to unix time in miliseconds, it is a lot easier to manipulate the time(add a day, week, month etc)...you can get more info about strtotime [here](http://nl3.php.net/strtotime) – zoranc Mar 08 '14 at 14:23
  • 1
    This question appears to be off-topic because it has too many errors to be solvable. More work needs to be done before this can be solved. – John Conde Mar 08 '14 at 14:35
  • @zoranc Thanks for pointing me in the right direction. Thats a huge help! Cheers. :D – Chris 'Pig' Hill Mar 08 '14 at 14:39
  • @zoranc - strtotime is not to be used for date math. The manual even says so. `DateTime()` is what should be used here. – John Conde Mar 08 '14 at 14:47
  • @JohnConde you are right, assuming he is working with php v5.3 or later, or `DateTime::modify()` with 5.2. And they don't say DO NOT USE..they simply state it is not advisable as there are the better ways of dealing with this in more recent versions of php...however based on what he is doing so far it will help him to start moving in the right direction. Correction to my previous comment:`strtotime` returns the amount of time in *seconds* – zoranc Mar 08 '14 at 14:55
  • `date->format("m/d/y h:m:i");` so `m` gives both months and minutes? – Mark Baker Mar 08 '14 at 15:07

0 Answers0