我有一個mySQL數據庫。計算兩個日期之間的天數
我需要計算兩個日期之間的天數。
我的客戶將通過php表格填寫輸入hm_date
與1979年1月1日創建一個新的記錄。
我需要一個字段total_days
來計算從hm_date
到當天的總天數。我需要這個領域隨時更新自己。
我該如何讓hm_date
與總天數一起出現並始終更新?
我asume這可以實現服務器端?
我應該用strototime()
?
我有一個mySQL數據庫。計算兩個日期之間的天數
我需要計算兩個日期之間的天數。
我的客戶將通過php表格填寫輸入hm_date
與1979年1月1日創建一個新的記錄。
我需要一個字段total_days
來計算從hm_date
到當天的總天數。我需要這個領域隨時更新自己。
我該如何讓hm_date
與總天數一起出現並始終更新?
我asume這可以實現服務器端?
我應該用strototime()
?
你需要使用MySQL的DATEDIFF()
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
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和結束日期$可以是任何有效的日期格式說明如下: 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";
是否有一個例子的任何地方的語法和如何寫它? – Erik
查看我的更新回答 –
是對的嗎? mysql> SELECT DATEDIFF('hm_date'); - > 1 mysql> SELECT DATEDIFF('total_days'); - > -31 – Erik