计算天数之间的差异*每天的价格=价值PHP

时间:2013-03-05 08:51:43

标签: php html forms checkout datediff

我目前正在制作一个允许人们预订宿舍住宿的小表格。基本上,我让他们选择两个日期。 (到达日和出发日)然后我想计算这些日期之间的差异,最后我想将天数乘以每天的价格。

我似乎无法弄清楚如何计算每天*每天的价格并将该字符串传递到我的表单中的“金额值”

这是我到目前为止所得到的:

<input type="text" id="datepicker" value="arrival (day-month-year)" />
<input type="text" id="datepicker2" value="departure (day-month-year)" />

<form action="checkout.php" method="post">
    <input name="amount" type="hidden" value="$dateDiff * price per day = value">
    <input type="submit" value="Check out" id="checkout">
</form>

我的PHP

<?php   
$date1 = ("#datepicker");
$date2 = ("#datepicker2");
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
echo "Difference is $fullDays days";  
?>

编辑:在前两个评论之后,让我解释一下,我对PHP很新。感谢。

3 个答案:

答案 0 :(得分:2)

datetime对象提供diff函数:

http://php.net/manual/en/datetime.diff.php

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
print_r($interval);
  

DateInterval对象   (       [y] =&gt; 0       [m] =&gt; 0       [d] =&gt; 2       [h] =&gt; 0       [i] =&gt; 0       [s] =&gt; 0       [invert] =&gt; 0       [天] =&gt; 2   )

所以你可以用

计算你的价格
$price = $pricePerDay * $interval->days;

答案 1 :(得分:2)

您必须将输入字段放在表单中并为其命名,如下所示:

<form action="checkout.php" method="post">
    <input type="text" id="datepicker" name="datepicker" value="arrival (day-month-year)" />
    <input type="text" id="datepicker2" name="datepicker2" value="departure (day-month-year)" />
    <input name="amount" type="hidden" value="$dateDiff * price per day = value">
    <input type="submit" value="Check out" id="checkout">
</form>

现在在你的PHP文件中:

<?php
  if(isset($_POST["datepicker"], $_POST["datepicker2"])){
    $date1 = new DateTime($_POST["datepicker"]);
    $date2 = new DateTime($_POST["datepicker2"]);
    $diff = $date1->diff($date2);
    $amount_per_day = 10; // for example 10 dollars
    $total = floor($diff["days"]) * $amount_per_day; // total
  }
?>

答案 2 :(得分:1)

试试这个:

function dateDiff($start, $end)
{
$start_ts = strtotime($start);
$end_ts = strtotime($end);
$diff = $end_ts - $start_ts;
return round($diff / 86400);
}