dongping1922 2015-05-23 20:05
浏览 134
已采纳

微秒,秒数为2位小数

I try calculate time of an act in second with 2 decimals.

protected function microtimeFormat($data)
    {
        $duration = microtime(true) - $data;
        $hours = (int)($duration/60/60);
        $minutes = (int)($duration/60)-$hours*60;
        return $seconds = $duration-$hours*60*60-$minutes*60;

    }

this method get start time as $data...and get back it an int second

for example it return 2second.

I try get second with 2 decimals ...

protected function microtimeFormat($data,$format=null,$lng=null)
    {
        $duration = microtime(true) - $data;
        $hours = (float)($duration/60/60);
        $minutes = (float)($duration/60)-$hours*60;
        $seconds = $duration-$hours*60*60-$minutes*60;
        return number_format((float)$seconds, 2, '.', '');
    }

but it return me 0.00 for short time

  • 写回答

2条回答 默认 最新

  • dsfd3546 2015-05-23 20:29
    关注

    I think your issue comes from the (float) conversion to $hours and $minutes. When you do so you don't save the decimal part of each so your calculation of $seconds always give 0. Convert to int so you actually save in $hours and $minutes the actual number of seconds they each represent. And the remainder goes to $seconds.

    protected function microtimeFormat($data,$format=null,$lng=null)
    {
        $duration = microtime(true) - $data;
        $hours = (int)($duration/60/60);
        $minutes = (int)($duration/60)-$hours*60;
        $seconds = $duration-$hours*60*60-$minutes*60;
        return number_format((float)$seconds, 2, '.', '');
    }
    
    $start = microtime(TRUE);
    sleep(1);
    $delay = $this->microtimeFormat($start);
    var_dump($delay);
    

    This gives me:

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

报告相同问题?

悬赏问题

  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置