这是我的代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1"><title>Day Calculator V 2.0</title>
</head>
<body>
<h1><p class="text-center"><strong>Esta es una calculadora de dias, funciona seleccionando de que mes a que mes quieres calcular los dias. </strong></p></h1>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method=post>
<div class="center-block text-center nofloat">
<input type=radio id="rad1" class="" name="tipfech" onclick="var divOne = document.getElementById('1');
divOne.style.visibility='hidden'" value="actual" checked> Usar fecha actual<br>
</div>
<div class="center-block text-center nofloat">
<input type=radio id="rad2" name="tipfech" onclick="var divOne = document.getElementById('1');
divOne.style.visibility='visible'" value="fecha"> Seleccionar fecha </div>
<div id="1" class="text-center">
<script>
var divOne = document.getElementById('1');
divOne.style.visibility='hidden';
</script>
Del
<input class="formachica form-control center-block" type="date" name="date1">
</div>
<div class="text-center">
Al
</div>
<input class="formachica form-control center-block" type="date" name="date2">
<br/>
<input type=submit class="center-block btn btn-primary" value="Submit"/>
</form>
<br/>
</div>
<div id="3" class="text-center">
<?php
$tipfech = $_POST[tipfech];
$da1 = $_POST[date1];
$da2 = $_POST[date2];
if ($tipfech == "actual"){
$yr1 = date("Y");
$month = date("m");
$day1 = date("d");
$date1 = new DateTime("$yr1-$month-$day1");
}
$date1 = new DateTime("$da1");
$date2 = new DateTime("$da2");
$interval = $date1->diff($date2);
echo "Son " . $interval->y . " años, " . $interval->m." meses, ".$interval->d." dias ";
// shows the total amount of days (not divided into years, months and days like above)
echo "<br/>"."Son " . $interval->days . " dias ";
?>
</div>
</body>
</html>
我的“fecha actual”是当前日期,所以当我选择该选项时,可以说是在 02/08/2015 (dd-mm-yy) 和第二个日期到 04/08/2015 它会返回一天,但如果我手动选择第一个日期(同 02/08/2015)它返回两天。
例子: http://monopolo11.ninja/tests/imgs/ (照片在那里,因为我名声不好,可以把它放在帖子里)
为什么会这样?
最佳答案
您总是覆盖 $date1
变量。
if ($tipfech == "actual"){
$yr1 = date("Y");
$month = date("m");
$day1 = date("d");
$date1 = new DateTime("$yr1-$month-$day1");
}
$date1 = new DateTime("$da1");
如果您不手动填写开始日期,则会使用参数 NULL
创建 new DateTime
。它返回当前日期,但带有实际时间。
这会导致计算日向下舍入(因为少了 48 小时)。
关于PHP 以不同的方式给我具有相同值的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31770417/