简体   繁体   English

在PHP中将小数小时添加到DateTime

[英]Add fractional hours to a DateTime in php

I have a system which I need to add a certain amount of fractional hours. 我有一个系统,需要增加一定数量的小数小时。 I've been searching and this is what I got, by far it's the most accurate method, but still doesn't give me the answer I need 我一直在搜索,这是我所得到的,到目前为止,这是最准确的方法,但是仍然无法提供我所需的答案

    function calculateHours($hours){

    $now =  new DateTime("2017-10-25 10:23:00");  
    $time = array();
    $time = explode(".", $hours);
    $time [1] += $time [0]*60;

    $now->modify("+".$time[1]." hours");

    return $now; 
}


$diff = 119.23;
$answer = calculateHours($diff);
echo $answer ->format('Y-m-d H:i:s');

The answer that I want to reach is "2017-11-09 11:00:00" and I receive "2017-10-25 12:22:23" instead 我想得到的答案是“ 2017-11-09 11:00:00”,而我收到的是“ 2017-10-25 12:22:23”

Adding the hours is not correct. 添加小时数不正确。 When you multiply hours times 60 it will make minutes. 当您将小时数乘以60时,将得出分钟数。

This code should work. 此代码应该起作用。

function calculateHours($hours){

    $now =  new DateTime("2017-10-25 10:23:00");
    $time = explode(".", $hours);
    $time[1] += $time[0]*60;

    $now->modify("+".$time[1]." minutes");

    return $now;
}


$diff = 119.23;
$answer = calculateHours($diff);
echo $answer->format('Y-m-d H:i:s');

Result is 2017-10-30 09:46:00 结果是2017-10-30 09:46:00

Use date_add 使用date_add

date_add($now, date_interval_create_from_date_string($tempo[1]' hours'));

or as object: 或作为对象:

 $now->add( DateInterval::createFromDateString($tempo[1].' hours'));

You should use DateInterval php class to create an inverval with x seconds from your $hours variable. 您应该使用DateInterval php类$hours变量中创建一个x秒的整数。

Then you just have to use the datetime add interval method to modify your date 然后,您只需要使用datetime添加间隔方法来修改日期

Please take a look a this example 请看一个例​​子

function calculateHours($hours){

    $now       =  new DateTime("2017-10-25 10:23:00");  
    var_dump($now);
    $timeParts = explode(".", $hours);
    // Where 23 is a percentage of on hour
    $minutes   = $timeParts[0] * 60 + round($time[1] * 60 / 100);
    // Where 23 is the number of minutes
    $minutes   = $timeParts[0] * 60 + $time[1];

    $interval = new DateInterval(sprintf('PT%dM', $minutes));
    $now->add($interval);
    echo $now->format('Y-m-d H:i:s');

    return $now; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM