简体   繁体   中英

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;

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 .

  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.

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;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM