开发者

Script to translate a mySQL datetime column to 'starts in x days/hours'

开发者 https://www.devze.com 2023-03-09 01:35 出处:网络
I have a MySQL table with events in it. Each event has a datetime column that i开发者_如何学运维ndicates when it starts.

I have a MySQL table with events in it. Each event has a datetime column that i开发者_如何学运维ndicates when it starts.

I'm looking for a way to produce a string similar to this using PHP:

'event X starts in 2 hours'

Should also work for days, weeks and months:

'event X starts in 5 days/weeks/months'


You should have some variable with the number of seconds till your date available. My example function is below.

<?php

function timeRemaining($total) {
 if (!$total || $total <= 0) return false;
 // define your ranges here (desc order), the keys will go to output.
 $elements = array(
  "years"   => 60*60*24*30*12,
  "months"  => 60*60*24*30,
  "weeks"   => 60*60*24*7,
  "days"    => 60*60*24,
  "hours"   => 60*60,
  "minutes" => 60,
  "seconds" => 1
 );
 // compute in a cycle to compress the code
 $return = array();
 foreach ($elements as $name => $dur) {
  $return[$name] = floor($total / $dur);
  $total -= $return[$name] * $dur;
 }
 // return data in the array form
 return $return;
}

// how much till new year?
echo "<pre>",
print_r(timeRemaining(mktime(0,0,0,1,1,2012)-time()));
echo "</pre>";

?>

Just copy-paste into any php file for testing, as an example it returns the array with years, months etc remaining till new year. You can tailor the output for your needs by feeding the return value to another string-generating function, just don't forget to check the value against false, which'll mean the time has passed.

Please note that the months use a simplified 30-days range, and the year here is set to 360 days, not 365.25 as in the real world.

Hope it will be of use.


To use this I first changed the format of the date to:

Select DATE_FORMAT(date_of, '%d/%m/%Y') as example from tbl

The php Function:

<?php
    function days_ago($time)
    {
        $today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $time_array = explode("/", $time);

       if(count($time_array) < 2)
       {
        $time = "N/A";
       }
       else
       {
         $time =   mktime(0, 0, 0, date($time_array[1]), date($time_array[0]), date($time_array[2]));
         $daysAgo = $today - $time;
         $time = ($daysAgo/86400);    
       }
       return $time;
    }
?>


I took the following snippet from the here.

<?php
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";
?>

$date1 would be the database date, $date2 would be the current date. Does that help?

0

精彩评论

暂无评论...
验证码 换一张
取 消