TheBlackBenzKid
TheBlackBenzKid

Reputation: 27087

PHP Calculate total days remaining via MySQL

My MySQL structure:

startdate
2012-01-01 04:00:00
enddate
2012-12-05 21:55:00

My PHP

$startDate=row['startdate'];
$endDate=row['enddate]';

$days="";
$days=date("Y-m-d H:i:s");
$days=($startDate-$endDate);
echo $days;

Upvotes: 1

Views: 1626

Answers (3)

siberiantiger
siberiantiger

Reputation: 305

You could use the strtotime() function to convert the start and end dates into seconds, subtract the start date from the end date, then use a bit of maths to convert seconds into days, and finally round off with the number of days with the floor() function. Here is a bit of code that I have written and tested.

<?php
$startDate = row['startdate'];
$endDate = row['enddate]';
$seconds_left = (strtotime($endDate) - strtotime($startDate));
$days_left = floor($seconds_left / 3600 / 24);
echo $days_left;
?>

Upvotes: 0

AndersTornkvist
AndersTornkvist

Reputation: 2629

Try this simple one-liner:

<?php
    echo round((strtotime($row['enddate'])-strtotime($row['startdate']))/86400);
?>

You could have a look in the PHP manual for strtotime() at http://php.net/manual/en/function.strtotime.php.

Upvotes: 4

mcmajkel
mcmajkel

Reputation: 313

  1. Why not use DATE_DIFF, a built-in, MySQL function?
  2. If you want to stick with PHP: first use strtotime() on both dates (convert to unix timestamp), then subtract, then format.

Upvotes: 1

Related Questions