php中以毫秒为单位的时间差计算 [英] Time difference calculation in milliseconds in php

查看:139
本文介绍了php中以毫秒为单位的时间差计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 PHP 编写的日志读取程序.我想计算任何给定的两条日志线的时间差.如果两次给出类似

I Have a log reading program written in PHP. I want to calculate the time difference of any given two log lines. I found lot of code for calculating the time difference if the two times are give like

$time1='10:15:30';和 $time2='10:15:35';.这里的时间差为 5 秒.

$time1='10:15:30'; and $time2='10:15:35';. here the time difference will be 5 seconds.

但这里我的输入时间将采用以下格式$time1='10:15:30:300';和 $time2='11:15:35:450';

But here my input times will be as in the following format $time1='10:15:30:300'; and $time2='11:15:35:450';

我想要一个函数来接收这个时间作为输入并给出以毫秒为单位的时间差.

I want a function which will receive this times as inputs and give the time difference in milliseconds.

是否有任何内置的 php 函数可以用于此目的?或者我们应该编写我们的自定义逻辑来拆分这个时间然后计算差异?

Is there any inbuilt php function that can be utilized for this purpose ? or should we write our custom logic to split this time and then calculate the difference ?

推荐答案

一开始,你的时间写错了.毫秒前应该有小数点.

At first, your times are written wrong. There should be decimal dot before milliseconds.

这意味着会有时间

10:15:30.300 和 11:15:35.450

10:15:30.300 and 11:15:35.450

代替

10:15:30:300 和 11:15:35:450

10:15:30:300 and 11:15:35:450

但是在下面写的课程中,您可以改进模式以使其适合您的时间格式.或更改整个检查.

But in class written below you could improve pattern to it would fit your time formatting. Or change whole checking.

对于类似的情况,我最近不得不解决(读取由智能手机/平板电脑 app IoTools 创建的 csv 文件并计算时间之间的毫秒差异),并基于问题 如何获得以毫秒为单位的时间差,我准备了这样做的类 - 但仅限于 1 的范围内天(24 小时).

For similar case I had to solve very recently (reading of csv files created by smartphone/tablet app IoTools and counting milliseconds differences between times), and based on question How to get time difference in milliseconds, I prepared class that does it - but only within range of one day (24 hours).

它并不完美(因为它可以有更多的选择)但它计算得很好(我希望它做得很好,我没有对其进行太多测试).

It is not perfect (as it could get some more options) but it computes well (I hope that it does well, I have not tested it much).

对于这个答案,我删除了抛出异常的详细信息,并通过它们的值重写了一些常量.我也删除了注释以缩短代码,但用描述性文本替换它们.

For this answer, I deleted details of exceptions throwing and rewrote some constants by their values. Also I deleted annotations to make code shorter, but replaced them with descripting texts.

class DayTimeCount
{

时间转换为毫秒.因此,这两个变量可以输入为integer.

Times are converted into milliseconds. So, these two variables may be typed as integer.

    protected $Time_Start = 0;
    protected $Time_End = 0;

时间尺度也可以是整数.这个变量的名称可能有点不幸,因为它没有完全正确地说明它的用途.

Also time scale may be as integer. Name of this variable may be a bit unfortunate, as it is not fully correctly saying for what purpose it is used.

    protected $Time_Scale = 1;

这个变量可以是一个常量.它的内容根本没有改变.

This variable could be a constant. Its content is not changed at all.

    private $TimePattern = '/(?<Hours>[0-9]{2})\:(?<Minutes>[0-9]{2})\:(?<Seconds>[0-9]{2}).(?<Milliseconds>[0-9]{0,3})/';

此功能用于设置开始时间(开始时间间隔需要计算的时间).检查时间是否设置正确模式后(如上面写的字符串对应模式,不是整数),将时间转换为毫秒.

This function is for setting of start time (time when starts interval you need to count). After checking if time is set in correct pattern (as string corresponding pattern writen above, not integer), time is converted into milliseconds.

    public function Set_StartTime($Time = NULL)
    {
        try
        {
            if( !preg_match($this -> TimePattern, $Time, $TimeUnits) )
            {
                throw new Exception(/* some code */);
            }
        }
        catch( Exception $Exception )
        {
            $Exception -> ExceptionWarning(/* some code */);
        }

        $this -> Time_Start = ($TimeUnits['Hours'] * 60 * 60 * 1000) + ($TimeUnits['Minutes'] * 60 * 1000) + ($TimeUnits['Seconds'] * 1000) + $TimeUnits['Milliseconds'];
    }

此功能与前面类似,但用于设置结束时间(结束间隔的时间需要计算).

This function is similar to previous, but for setting of end time (time when ends interval you need to count).

    public function Set_EndTime($Time = NULL)
    {
        try
        {
            if( !preg_match($this -> TimePattern, $Time) )
            {
                throw new Exception(/* some code */);
            }
        }
        catch( Exception $Exception )
        {
            $Exception -> ExceptionWarning(/* some code */);
        }

        $this -> Time_End = ($TimeUnits['Hours'] * 60 * 60 * 1000) + ($TimeUnits['Minutes'] * 60 * 1000) + ($TimeUnits['Seconds'] * 1000) + $TimeUnits['Milliseconds'];
    }

此功能用于设置时间刻度.它有助于将毫秒转换为秒(精度为毫秒)或分钟或小时.

This function is for setting of time scale. It helps to convert milliseconds to seconds (with precision of milliseconds) or minutes or hours.

静态函数 Check_IsTimeScale 是我自己的函数,用作 in_array().

Static function Check_IsTimeScale is my own function that works as in_array().

    public function Set_TimeScale($Scale = 1)
    {
        try
        {
            if( !Core::Check_IsTimeScale($Scale) )
            {
                throw new Exception(/* some code */);
            }
        }
        catch( Exception $Exception )
        {
            $Exception -> ExceptionWarning(/* some code */);
        }

        $this -> Time_Scale = $Scale;
    }

最后,函数用于自己计算时差.它只有三个步骤.

And finally, function is for own counting of time difference. It has only three steps.

    public function Execute()
    {

第一个是自己计数.如果 end 和 start 之间的差为正数(大于零),则按原样处理.

The first one is own counting. If difference between end and start is positive number (greater than zero), it is taken as it is.

但是如果 end 和 start 之间的差值为负(因为 end 在午夜之后而 start 在午夜之前,例如 00:00:00.658 和 23:59:59:354),则需要使用附加计数.区分一天中的开始时间和完整时间 - 并添加结束时间.

But if difference between end and start is negative (as end is after midnight and start is before midnight, for example 00:00:00.658 and 23:59:59:354), then it is needed to use additional counting. To make difference between start and full time of day - and add end time.

    $Diff = $this -> Time_End - $this -> Time_Start;

    if( $Diff < 0 )
    {
        $Diff = $this -> Time_End + (86400000 - $this -> Time_Start);
    }

第二步,时间尺度的应用.以毫秒为单位的时间除以时间刻度.如果除以 1,结果(当然)与原始数字相同,并且没有四舍五入.如果除以更大的数字(允许选项为 1000 或更大),则四舍五入到用于划分它的数字的长度.

The second step, application of time scale. Time in milliseconds is divided by time scale. If it is divided by 1, result is (of course) the same as original number and it is no rounded. If it is divided by larger number (1000 or greater from allowed options), it is rounded to length of number used to divide it.

        $Diff = round($Diff / $this -> Time_Scale, strlen($this -> Time_Scale));

第三步是返回最终结果.可能它可以与上一步合并,但现在它(至少)可读性更好.

Third step is returning of final result. Probably it could be merged with previous step, but now it is (at least) better readable.

        return $Diff;
    }
}

函数ExceptionWarning也是我的函数,可以换成你自己的.

Function ExceptionWarning is also my function, and can be replaced by your own one.

这篇关于php中以毫秒为单位的时间差计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆