我正在测试我是否可以根据帖子获取并显示两个日期之间的持续时间。这两个日期是从数据库中调用的。
这是在我点击"更新合同" 之前。
这是在我点击了"更新合同" 之后。
腓:
<?php
require("config.php");
$id = filter_input(INPUT_GET, 'id');
error_reporting( ~E_NOTICE );
if(isset($_POST['edit']) ){
$startdate = date('Y-m-d', strtotime($_POST['startdate']));
$expdate = date('Y-m-d', strtotime($_POST['expdate']));
$diff = abs(strtotime($expdate) - strtotime($startdate));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$upd= "UPDATE `contracts` SET `startdate` = ?, `expdate` = ? WHERE `id` = ?";
$stmt = $con->prepare($upd);
$stmt->bind_param("ssi",$startdate,$expdate,$id);
$stmt->execute();
if ($stmt->errno){
echo "FAILURE!!! " . $stmt->error;
} else {
$successMsg = "Contract Successfully Updated!";
}
$stmt->close();
}
printf("%d years, %d months, %d days\n", $years, $months, $days);
?>
形式:
<form method="post" action="">
<?php
if(isset($successMsg)){
?>
<div class="alert alert-success">
<strong><?php echo $successMsg; ?></strong>
<?php
}
?>
<?php
$id = filter_input(INPUT_GET, 'id');
$sql = "SELECT * FROM contracts WHERE `id` = $id";
$result = $con->query($sql);
$row = $result->fetch_assoc();
?>
<label>Start Date</label>
<input type="date" name="startdate" value="<?php echo $row['startdate']; ?>"/>
<label>Expiry Date</label>
<input type="date" name="expdate" value="<?php echo $row['expdate']; ?>"/>
<button type="submit" class="btn btn-success btn-md" name="edit">
<span class="glyphicon glyphicon-pencil"></span> Update Contract
</button>
</form>
问题是:
答案 0 :(得分:0)
回答第二个问题:
使用原生DateTime Class并与之相关DateInterval:
<?php
$startdate=new DateTime($_POST['startdate']);
$expdate=new DateTime($_POST['expdate']);
$diff=$expdate->diff($startdate);
print_r( $diff );
// or
printf("%d years, %d months, %d days\n", $diff->y, $diff->m, $diff->d);
// for database input you'll have to format the dates like so:
echo $startdate->format('Y-m-d');
第一个问题的解决方案就是重构您的代码 我想这都是一个php文件。
$startdate = $row['startdate']
;)