Php 如何将十进制转换为时间
我正在使用php并尝试将十进制转换为timehh:mm 但它不适用于任何代码和测试,原始字符串来自excel 例如: 这很简单。要将小数转换为小时,请与24相乘Php 如何将十进制转换为时间,php,time,Php,Time,我正在使用php并尝试将十进制转换为timehh:mm 但它不适用于任何代码和测试,原始字符串来自excel 例如: 这很简单。要将小数转换为小时,请与24相乘 $hours = $dec * 24; 现在,要将小数转换为小时:分钟,请使用以下命令: function convertTime($dec) { // start by converting to seconds $seconds = ($dec * 3600); // we're given hours,
$hours = $dec * 24;
现在,要将小数转换为小时:分钟,请使用以下命令:
function convertTime($dec)
{
// start by converting to seconds
$seconds = ($dec * 3600);
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}
echo convertTime($hours);
资料来源:
输出:我通常建议对任何日期算法使用DateTime类,而不是手动计算。它将考虑任何夏令时/等,尽管您的问题不清楚是否需要这样做
<?php
/**
* @param float $x Decimal number of hours
* @return string HH:mm
*/
function dec_hours($x) {
$sec = intval($x * (24 * 60 * 60));
$date = new DateTime("today +$sec seconds");
return $date->format('H:i');
}
echo dec_hours(0.625); // 15:00
echo dec_hours(0.53541666666667); // 12:51
echo dec_hours(0.40277777777778); // 09:40
0.625怎么等于15:00?哦,我知道了,0.625*24=15你能展示一下你的代码吗?
function convertTime($dec)
{
// start by converting to seconds
$seconds = ($dec * 3600);
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}
echo convertTime($hours);
<?php
/**
* @param float $x Decimal number of hours
* @return string HH:mm
*/
function dec_hours($x) {
$sec = intval($x * (24 * 60 * 60));
$date = new DateTime("today +$sec seconds");
return $date->format('H:i');
}
echo dec_hours(0.625); // 15:00
echo dec_hours(0.53541666666667); // 12:51
echo dec_hours(0.40277777777778); // 09:40