[英]How to convert Birth date to age ( years, months, days ) and age( years, months, days ) to birth date conversion in PHP?
[英]PHP - how to display years,months and days based on two POST date?
我正在測試是否可以獲取並顯示基於發布的兩個日期之間的持續時間。 這兩個日期是從數據庫中調用的。
這是在我單擊“更新合同”之前 。
這是在我單擊“更新合同”之后 。
Php:
<?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>
問題是:
回答第二個問題:
利用本機DateTime類及其相關的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']
;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.