腾出时间

时间:2014-04-13 23:42:56

标签: php

我有一个剩余的时间功能,我用它来根据发送的参数获得剩余时间。我的问题是,如果有一天,一年或一个月,我很难计算。

功能:

  function get_time_difference_php_left($created_time)
 {
        $str = strtotime($created_time);
        $today = strtotime(date('Y-m-d H:i:s'));

        // It returns the time difference in Seconds...
        $time_differnce = $today-$str;

        // To Calculate the time difference in Years...
        $years = 60*60*24*365;

        // To Calculate the time difference in Months...
        $months = 60*60*24*30;

        // To Calculate the time difference in Days...
        $days = 60*60*24;

        // To Calculate the time difference in Hours...
        $hours = 60*60;

        // To Calculate the time difference in Minutes...
        $minutes = 60;

        if(intval($time_differnce/$years) > 1)
        {
            return " - ". intval($time_differnce/$years)." years left";
        }else if(intval($time_differnce/$years) > 0)
        {
            return " - ".intval($time_differnce/$years)." year left";
        }else if(intval($time_differnce/$months) > 1)
        {
            return " - ".intval($time_differnce/$months)." months left";
        }else if(intval(($time_differnce/$months)) > 0)
        {
            return " - ".intval(($time_differnce/$months))." month left";
        }else if(intval(($time_differnce/$days)) > 1)
        {
            return " - ".intval(($time_differnce/$days))." days left";
        }else if (intval(($time_differnce/$days)) > 0) 
        {
            return " - ".intval(($time_differnce/$days))." day left";
        }else if (intval(($time_differnce/$hours)) > 1) 
        {
            return " - ".intval(($time_differnce/$hours))." hours left";
        }else if (intval(($time_differnce/$hours)) > 0) 
        {
            return " - ".intval(($time_differnce/$hours))." hour left";
        }else if (intval(($time_differnce/$minutes)) > 1) 
        {
            return " - ".intval(($time_differnce/$minutes))." minutes left";
        }else if (intval(($time_differnce/$minutes)) > 0) 
        {
            return " - ".intval(($time_differnce/$minutes))." minute left";
        }else if (intval(($time_differnce)) > 1) 
        {

            return " - ".intval(($time_differnce))." seconds left";
        }else
        {
            return " - few seconds left";
        }
  }

如果我根据现在的时间和日期时间2014-04-17 03:27:26运行此操作,它会告诉我88 years

建议,想法?

2 个答案:

答案 0 :(得分:1)

你最初有三月。你正在向后计算。您的代码应显示到期日期,而不是创建日期。如果您尝试使用过期日期,那么您的代码应使用:

$time_differnce = $str - $today;

您可以在每个if中使用模数(余数)运算符来显示下一个值。例如,如果您有3.7天,则使用3天,然后使用.7*$hours

答案 1 :(得分:-1)

将所有其他if语句更改为if'

更改自:

if(intval($time_differnce/$years) > 1) {
    return " - ". intval($time_differnce/$years)." years left";
} else if (intval($time_differnce/$years) > 0) {

if(intval($time_differnce/$years) > 1) {
    return " - ". intval($time_differnce/$years)." years left";
} 
if (intval($time_differnce/$years) > 0) {