i am using the following code(based on this http://goo.gl/5HhSx) to calculate the difference between dates:
<?php
$date1 = '2012-03-29';
$date2 = '2012-04-02';
$datetime1 = date_create($date1);
$datetime2 = date_create($date2);
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%a days');
?>
The difference is 4 days.March has a fixed price(30€/day) and April has another(40€/day). Is there a way to sum the whole price? Three days until the end of march and another two from april? How can i add them correctly? Any help would be appreciated. Thanks.
For your exact example this works:
$date1 = '2012-03-29';
$dateBoundary = substr($date1, 0, 8).date('t', strtotime($date1));
$date2 = '2012-04-02';
$marchPrice = 30;
$aprilPrice = 40;
$datetime1 = date_create($date1);
$datetime1Boundary = date_create($dateBoundary);
$datetime2 = date_create($date2);
$interval1 = date_diff($datetime1, $datetime1Boundary);
$interval2 = date_diff($datetime1Boundary, $datetime2);
$totalPrice = ($interval1->format('%d') * $marchPrice) + ($interval2->format('%d') * $aprilPrice);
echo number_format($totalPrice, 2);
You can of course extrapolate the idea for periods which span multiple months.
Extract the month out of the date like this:
SELECT MONTH('8/14/04') as "Month";
for each date between '2012-03-29' and '2012-04-02' and then update the table accordingly. In case, you want to add up the sum then use a stored procedure -declare a variable 'sum' intitialized to zero and add by using switch cases like : CASE '04' then sum+=30 , CASE '03' then sum+=20
. Or,you can use an aggregate function too in your procedure for calculating.
Brief logic on achieving the target result.
Refer the mktime() and Date() functions