dongzhuxun5136 2012-03-29 10:23
浏览 42
已采纳

如何在计算日期之间的差异后为每个日期分配价格? (date_diff)

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.

  • 写回答

3条回答 默认 最新

  • dongyu1614 2012-03-29 10:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面