問題描述
如果條件在幾小時、幾天內不起作用 (if condition not working for Hours,Days)
見下面的代碼,如果條件不工作,從這段代碼中,我不知道如何寫這個的 if 條件
<?php
$start = $row['t_started_on'];
$due = date('Y‑m‑d H:i:s');
$start_date = new DateTime($start);
$end_date = new DateTime($due);
$interval = $start_date‑>diff($end_date);
echo "Result " . $interval‑>y . " years, " . $interval‑>m." months, ".$interval‑>d." days ";
// upto here i got correct answer.
if($interval‑>h <="24"){
$result = $interval‑>h." Hours";// i want like this 10 Hours ago
}else if ($interval‑>d <="30")){
$result = $interval‑>d." Days";// i want like this 25 Days ago
}else{
$result = $interval‑>m." Months";// i want like this 10 Months ago
}
?>
參考解法
方法 1:
Please try this
<?php
$start = $row['t_started_on'];
$due = date('Y‑m‑d H:i:s');
$start_date = new DateTime($start);
$end_date = new DateTime($due);
$interval = $start_date‑>diff($end_date);
echo "Result " . $interval‑>y . " years, " . $interval‑>m." months, ".$interval‑>d." days ";
// upto here i got correct answer.
if($interval‑>h <= 24){ // Removed quotes
$result = $interval‑>h." Hours";// i want like this 10 Hours ago
}
else if ($interval‑>d <= 30)){ // Removed quotes
$result = $interval‑>d." Days";// i want like this 25 Days ago
}
else{
$result = $interval‑>m." Months";// i want like this 10 Months ago
}
?>
方法 2:
Hi,
One things that we have to check ,is t_started_on coming in Y‑m‑d H:i:s format ?.
Please try this.it should work.
<?php
$start = $row['t_started_on'];
$due = date('Y‑m‑d H:i:s');
$start_date = new DateTime($start);
$end_date = new DateTime($due);
$interval = $start_date‑>diff($end_date);
echo "Result " . $interval‑>y . " years, " . $interval‑>m." months, ".$interval‑>d." days ";
// upto here i got correct answer.
if($interval‑>h <= 24){
$result = $interval‑>h." Hours";// i want like this 10 Hours ago
}else if ($interval‑>d <= 30){
$result = $interval‑>d." Days";// i want like this 25 Days ago
}else{
$result = $interval‑>m." Months";// i want like this 10 Months ago
}
?>
Here's example.
$start = '2016‑03‑02 12:00:00 PM';
$due = date('Y‑m‑d H:i:s');
echo $due;
$start_date = new DateTime($start);
$end_date = new DateTime($due);
$interval = $start_date‑>diff($end_date);
echo "Result " . $interval‑>y . " years, " . $interval‑>m." months, ".$interval‑>d." days ";
// upto here i got correct answer.
if($interval‑>h <= 24 ){
$result = $interval‑>h." Hours";// i want like this 10 Hours ago
}else if ($interval‑>d <= 30 ){
$result = $interval‑>d." Days";// i want like this 25 Days ago
}else{
$result = $interval‑>m." Months";// i want like this 10 Months ago
}
i got this result : Result 0 years, 0 months, 30 days 21 Hours,it looks liek correct result.
Note : Result may be vary due to timezone.
</code></pre>
(by Kani R、dhi_m、Mahendra Sharma)
參考文件