计算两个日期之间的天数

时间:2012-05-11 00:28:22

标签: php mysql date days

我有一个mySQL数据库。

我需要计算两个日期之间的天数。

我的客户将在1979年1月1日通过php表单填写输入hm_date以创建新记录。

我需要一个字段total_days来计算从hm_date到现在的总天数。我需要这个字段总是每天更新自己。

如何使hm_date显示总天数并始终更新?

我认为这可以在服务器端实现吗?

我应该使用strototime()吗?

3 个答案:

答案 0 :(得分:8)

您需要使用MySQL的DATEDIFF()

  

DATEDIFF()返回expr1 - expr2,表示为从一天开始的值   约会到另一个。 expr1和expr2是日期或日期和时间   表达式。只有值的日期部分用于   计算

mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
        -> 1
mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');
        -> -31

根据您的问题,我认为您需要DATE_DIFF(hm_date, CURRENT_DATE)。只需确保hm_date格式为YYYY-MM-DD

答案 1 :(得分:1)

使用PHP:

$daydiff = floor( ( strtotime( $endDate ) - strtotime( $startDate ) ) / 86400 );

$ startDate和$ endDate可以是这里解释的任何有效日期格式: http://www.php.net/manual/en/datetime.formats.date.php

答案 2 :(得分:1)

它非常容易但很长..请遵循以下代码

<?php

  // Set timezone
  date_default_timezone_set("UTC");

  // Time format is UNIX timestamp or
  // PHP strtotime compatible strings
  function dateDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
      $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
      $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
      $ttime = $time1;
      $time1 = $time2;
      $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
      // Set default diff to 0
      $diffs[$interval] = 0;
      // Create temp time from time1 and interval
      $ttime = strtotime("+1 " . $interval, $time1);
      // Loop until temp time is smaller than time2
      while ($time2 >= $ttime) {
    $time1 = $ttime;
    $diffs[$interval]++;
    // Create new temp time from time1 and interval
    $ttime = strtotime("+1 " . $interval, $time1);
      }
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
      // Break if we have needed precission
      if ($count >= $precision) {
    break;
      }
      // Add value and interval 
      // if value is bigger than 0
      if ($value > 0) {
    // Add s if value is not 1
    if ($value != 1) {
      $interval .= "s";
    }
    // Add value and interval to times array
    $times[] = $value . " " . $interval;
    $count++;
      }
    }

    // Return string with times
    return implode(", ", $times);
  }

?>

现在尝试一下,看看它是如何显示差异的......

echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";