doubiaode0460 2014-04-12 18:24
浏览 27
已采纳

PHP OOP DateTime ModifyDate小数位错误

If I use the following code

$averageWeeks = 2.7;
$laidDate->modify('+'.$averageWeeks.' week');

I get the date 31st May 2014 returned, whereas if i use the following code

$averageWeeks = 3;
$laidDate->modify('+'.$averageWeeks.' week');

I get the date 3rd May 2014 which is right. Is there any way I can use decimal places in the date modify method?

  • 写回答

1条回答 默认 最新

  • duanlu1793 2014-04-12 18:48
    关注

    Assuming you're starting at April 12th, then May 3rd would be 3 weeks and May 31st would be 7 weeks. So my guess is that when you pass "2.7", it is ignoring the "2." portion of that string.

    You could consider calculating the number of days to add separately, such as:

    $averageWeeks = 2.7;
    $averageDays = floor($averageWeeks * 7);
    $laidDate->modify('+'.$averageDays.' days');
    

    Consider also that 2.7 weeks is 18.9 days. By taking the floor, We are adding 18 days. It doesn't make since to add fractional days here, unless you intend to change the time of day as well. If you did, you'd have to do some additional math, as it doesn't appear that either modify or add will support fractional values. You could do something like this:

    $averageWeeks = 2.7;
    $averageSeconds = floor($averageWeeks * 7 * 24 * 60 * 60);
    $laidDate->modify('+'.$averageSeconds.' seconds');
    

    But you might be fooling yourself if you think this time is accurate, since not every local day has exactly 24 hours in it, due to daylight saving time transitions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 禁止修改windows系统时间
  • ¥50 kinect连接win11笔电导致音视频设备消失
  • ¥15 python线性查找题
  • ¥20 GDB info thread 显示格式问题
  • ¥15 WiFi串口通信问题
  • ¥15 基于python建立整数线性规划问题并求解
  • ¥30 Semantic Kernel + OllamaSharp 集成本地大语言模型
  • ¥15 channels运行加载异常
  • ¥15 用C语言实现语音的读取及播放
  • ¥15 poi怎么在指定位置之后生成多个表格