我想在PHP
用户输入日期DD-MM-YYYY
我有一个天差计算器,但它计算两个指定年份之间的天数。
$daysfrom = $_POST['daysfrom'];
$daysto = $_POST['daysto'];
echo 'Difference of days B.W <b>' . $daysfrom . '</b>-<b>'.$daysto.'</b> are';
$daysto = strtotime($daysto);
$daysfrom = strtotime($daysfrom);
$datediff = $daysto - $daysfrom;
echo floor($datediff / (60 * 60 * 24));
我已经尝试过计算生日之间的天数。(我知道这不对)
用户将输入MM-DD-YYYY
,并且应计算月之间的天数。
例如: 输入: 13-03-1993
输出(假设今天的日期 10-03-2014 ),它应显示03 Days left
if (isset($_POST['daysto'])) {
$daysto = $_POST['daysto'];
echo 'Your birthday comes within ';
$daysto = strtotime($daysto);
$now = strtotime(date('d-m'));
$datediff = $daysto - $now;
echo $datediff / 60 / 60 / 24;
}
答案 0 :(得分:1)
您可以将出生日期更改为与当前日期相同的年份,然后运行date_diff()。
$birthdate = strtotime("13-03-1993");
$today = strtotime("10-03-2014");
$fixedBirthdate = date_create(date("Y", $today) . "-" . date("m", $birthdate) . "-" . date("d", $birthdate));
$diff = date_diff(date_create(date("d-m-Y", $today)), $fixedBirthdate);
echo $diff->format("%R%a days");
可能有一种简化其中一些方法的方法。我整体上使用PHP语法并不是那么好。
编辑:通过使用date_parse_from_format(),我可能会沿着这些方向做点什么。
注意:这适用于&#34; 13-03-1993&#34;并且只是&#34; 13-03&#34;。
$birthdateArray = date_parse_from_format("d-m-Y", "13-03");
$todayArray = date_parse_from_format("d-m-Y", "10-03-2014"); //In the real thing, this should instead grab the actual current date
$birthdate = date_create($todayArray["year"] . "-" . $birthdateArray["month"] . "-" . $birthdateArray["day"]);
$today = date_create("10-03-2014"); //This should also be actual current date
$diff = date_diff($today, $birthdate);
echo $diff->format("%R%a days");
答案 1 :(得分:-1)
你使用这种方法。
$birthdate = "25-05-1993"; // desired input DD-MM-YYYY
// $birthdate = "25-05-".(date('Y')-1); if input DD-MM
$current_date = date("d-m-Y"); // current date
$birth_time = strtotime($birthdate);
$current_time = strtotime($current_date);
$arr1 = explode("-", $birthdate);
$year1 = $arr1[2];
$arr2 = explode("-", $current_date);
$year2 = $arr2[2];
$year_diff = $year2-$year1;
$time_new = strtotime("+".$year_diff." year", $birth_time);
if($time_new<$current_time)
{
$time_new = strtotime("+1 year", $time_new);
}
$time_diff = $time_new - $current_time;
$days = $time_diff/86400;
echo "Days Left:".$days; // output
INPUT 25-05-1993 输出:剩余天数:1 INPUT: 20-04-1993 输出:剩余天数:331
参见 DEMO