我有一个 mySQL 数据库。
我需要计算两个日期之间的天数。
我的客户将通过 php 表单填写 1979 年 1 月 1 日的输入hm_date
以创建新记录。
我需要一个字段total_days
来计算从hm_date
今天到现在的总天数。我需要这个字段每天都在更新自己。
如何使hm_date
总天数显示并始终更新?
我想这可以在服务器端实现吗?
我应该使用strototime()
吗?
你会想要使用 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
格式。
使用 PHP:
$daydiff = floor( ( strtotime( $endDate ) - strtotime( $startDate ) ) / 86400 );
$startDate 和 $endDate 可以是此处解释的任何有效日期格式: http ://www.php.net/manual/en/datetime.formats.date.php
它很容易但很长..请遵循以下代码
<?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";