dongza1708 2018-09-27 14:13
浏览 11

以分钟为单位的Unix时差会产生意外结果

I have the following simple code for testing:

$start_time_unix = time();
$end_time_unix = time();
$seconds_diff = $end_time_unix - $start_time_unix;    
$duration = round(abs($seconds_diff/1000) / 60,2);

When i store it in MySQL (int), the results are big values like 25634 even for a few seconds. How can i get the minutes, even in fraction of minutes?? What is wrong with my code above ??

  • 写回答

2条回答 默认 最新

  • dsbm49845 2018-09-27 14:18
    关注

    First of all int cannot store fractions, so you will probably want to use float or double instead.

    But why are you dividing by 1000. $seconds_diff consists of a seconds, so dividing by 60 will give you fraction of a minute.

    For example: If $seconds_diff is a value of 13 [seconds]:

    $duration_in_minutes = round($seconds_diff / 60, 2);
    $duration_in_milliseconds = $seconds_diff * 1000;
    

    If it is your goal to use milliseconds then use microtime() instead of time(): http://php.net/manual/de/function.microtime.php

    Recommendation
    Just measure the time with microtime() and directly store the result in the database without rounding, dividing or formatting. Then later on, do the formatting when you have to output it. This will give you more precise results and more freedom.

    $start_time = microtime();
    …
    $end_time = microtime();
    $duration = $end_time - $start_time; // duration in milliseconds --> save to database
    

    When outputting, for example:

    $duration = get_duration_from_database(); // pseudo function
    printf('%.2f minutes', $duration / 1000 / 60);
    
    评论

报告相同问题?