The function issues "1 day 7 hours 1 minute 32 seconds ago." How to make it so that if 1 day (24 hours) has passed, then the conclusion is "1 day ago."; if a week has passed then "1 week ago" ...

In short, if one day has not passed, let him print "7 hours 1 minute 32 seconds ago"; if it was "1 day ago," "2 weeks ago," etc. ....

function showDate( $date ) // $date --> время в формате Unix time { $stf = 0; $cur_time = time(); $diff = $cur_time - $date; $seconds = array( 'секунда', 'секунды', 'секунд' ); $minutes = array( 'минута', 'минуты', 'минут' ); $hours = array( 'час', 'часа', 'часов' ); $days = array( 'день', 'дня', 'дней' ); $weeks = array( 'неделя', 'недели', 'недель' ); $months = array( 'месяц', 'месяца', 'месяцев' ); $years = array( 'год', 'года', 'лет' ); $decades = array( 'десятилетие', 'десятилетия', 'десятилетий' ); $phrase = array( $seconds, $minutes, $hours, $days, $weeks, $months, $years, $decades ); $length = array( 1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600 ); for ( $i = sizeof( $length ) - 1; ( $i >= 0 ) && ( ( $no = $diff / $length[ $i ] ) <= 1 ); $i -- ) { ; } if ( $i < 0 ) { $i = 0; } $_time = $cur_time - ( $diff % $length[ $i ] ); $no = floor( $no ); $value = sprintf( "%d %s ", $no, getPhrase( $no, $phrase[ $i ] ) ); $value = ''; for (; $i >= 0; $diff %= $length[$i--]) { $no = floor($diff / $length[$i]); $value .= sprintf("%d %s ", $no, getPhrase($no, $phrase[$i])); } return $value . ' назад'; } function getPhrase( $number, $titles ) { $cases = array( 2, 0, 1, 1, 1, 2 ); return $titles[ ( $number % 100 > 4 && $number % 100 < 20 ) ? 2 : $cases[ min( $number % 10, 5 ) ] ]; } 
  • And what does mysql have to do with the question? - Mike
  • In general, try the actions that in the last for perform only 1 time - Mike
  • Well, it will output 1 day ago 2 weeks ago ... but I need to do something through if if it is a check if 1 day did not pass then 1 hour 2 minutes 12 seconds to issue a type - Sauron
  • Well, I call it (not corrected) from time()-10000 perfectly gives out '2 hours 46 minutes 40 seconds ago'. As if everything is correct, one day did not pass, and she issued it from the clock - Mike
  • one
    mysql has nothing to do with it. for reference just like, 5 minutes ago, yesterday, etc. usually use javascript, because only it will allow you to change the labels in real time without refreshing the page. see the timeago extension. By the way, it has Russian localization. github.com/rmm5t/jquery-timeago - artoodetoo

1 answer 1

From larger to smaller build a cascade of conditions, like this:

 if( $diff > 86400) { echo "N дней назад"; } else if( $diff > 3600) { echo "N часов назад"; } else if( $diff > 60) { echo "N минут назад"; } else { echo "N секунд назад"; }