1

I'm trying to get remaining Days, hours and minutes to a certain date using php.

However i get a very strange output from my code which looks like this:

-16828 days and -11 hours and -21 minutes and -24 seconds 

The future dates are stored in the mysql database in this format:

29/01/2016 7pm

So I went ahead and done this:

$Draw_time = "29/01/2016 7pm";

$date = $Draw_time;
$timestamp = strtotime($date);
$new_date = date('Y-m-d a',$timestamp );

$seconds = strtotime($new_date) - time();

$days = floor($seconds / 86400);
$seconds %= 86400;

$hours = floor($seconds / 3600);
$seconds %= 3600;

$minutes = floor($seconds / 60);
$seconds %= 60;


echo "$days days and $hours hours and $minutes minutes and $seconds seconds";

But when i run this code, I get the above strange output!

I understand that this could be because of a number reasons but the only thing i could think of is the fact that I am using a in my format?

Could someone please advise on this issue?

rooz
  • 361
  • 1
  • 8
  • 22

3 Answers3

4

Simply use DateTime class like as

$Draw_time = "29/01/2016 7pm";

$date = DateTime::createFromFormat("d/m/Y ha",$Draw_time);
$date2 = new DateTime();

echo $diff = $date2->diff($date)->format("%a days and %H hours and %i minutes and %s seconds");
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0

Try this

<?php 

    $Draw_time = str_replace('/', '-', "29/01/2016 7pm");

    $now = new DateTime();

    $futureDate = new DateTime($Draw_time);

    $interval = $futureDate->diff($now);
    echo $interval->format("%a days %h hours %i minutes %s seconds");
?>
jameshwart lopez
  • 2,993
  • 6
  • 35
  • 65
0

Try this.

$draw_time = "2016/01/29 7pm";
$date_time = explode(" ", $draw_time);// make separate date and time in array
$date = strtotime($date_time[0]); // convert your date(2016/01/29) into php time
$time = strtotime($date_time[1]); // convert your time(7pm) into php time
$date = $date + $time; // make total time to count
$new_Date = $date - (time()); // convert into difference from current time
$day = $new_Date % 86400;
$hrs = $new_Date % 3600;
$min = $new_Date % 60;
echo "Day= ".(date("d",$day));
echo " Hours= ".(date("h",$hrs));
echo " Minutes= ".(date("i",$min));
pratik
  • 49
  • 1
  • 7