-4

所以我有几个包含工作时间的 HTML 字段。例如,用户可以输入08:15(应该给我8.25)和12:30(应该给我12.5)。

这将如何完成?我正在考虑将开始日期定为 1970 年 1 月 1 日,添加小时数,将其转换为时间戳,然后进行其他数学运算,但我不确定这是否正确,我什至可能会忽略一些(很明显) 功能。

4

3 回答 3

2
<?php

$string = "08:15";

$items = explode(":",$string);
$hours = intval($items[0]);
$minutes = intval($items[1]);

$decimalhours = $hours + ($minutes / 60);
echo $decimalhours;

This code is by no means robust as it fails when the user does not adhere to the strict syntax you're requiring. Nevertheless it should point you in the right direction.

于 2013-06-18T11:17:44.617 回答
2

It is not so tricky, so you may do it this way:

<?php
header('Content-Type: text/plain');

list($hours, $minutes) = explode(':', '12:30');

$hours += $minutes / 60;

echo $hours;
?>

And write your own function:

<?php

header('Content-Type: text/plain');

function time2dec($time, $delimiter = ':'){
    list($h, $m, $s) = array_pad(explode($delimiter, $time), 3, 0);
    return $h + $m / 60 + $s / 3600;
}

echo time2dec('12:30'), PHP_EOL;
echo time2dec('12:15'), PHP_EOL;
echo time2dec('12:15:15'), PHP_EOL;
echo time2dec('12:a:15'), PHP_EOL;
?>

Shows:

12.5
12.25
12.254166666667
12.004166666667
于 2013-06-18T11:18:03.853 回答
2

I will give you the idea how it can be calculated (Expect you to code :D)

  1. Let MM part be x
  2. Now your result will be y= 5/3 * x

    So as an example, if it is 8:15, then
    x = 15
    y = 5/3*15 = 25
    so the result is 8.25

于 2013-06-18T11:18:06.067 回答