在php中将一年中的某一天转换为datetime

时间:2014-04-22 13:03:07

标签: php datetime

我有价值

$days = 166.0444; 

这是一年中的某一天。如何将此值简单地转换为其日期时间,该日期时间应为

2013-06-15 01:04:ss 

?当然,我可以减去一个月的天数来获得月份,然后继续几天等等,但还有其他方法吗?

编辑:年份将始终是当前年份

谢谢大家,我就这样做了:

$dayOfYear = (int)$result;
$temp =  ($result - $dayOfYear) * 24;
$hours = (int)$temp;
$temp = ($temp - $hours) * 60;
$minutes = (int)$temp;
$temp = ($temp - $minutes) * 60;
$seconds = (int)$temp;

$date = new DateTime();
$date->add(new DateInterval('P' . $dayOfYear . 'D'));
$date->add(new DateInterval('PT' . $hours . 'H'));
$date->add(new DateInterval('PT' . $minutes . 'M'));
$date->add(new DateInterval('PT' . $seconds . 'S'));

2 个答案:

答案 0 :(得分:1)

你可以用这种或类似的方式做到:

function convertDaysToDateTime($days, $year){
    $datetime = new DateTime();
    return $datetime->setTimestamp(mktime(0,0,0,0,0,$year) + $days * 24 * 3600);
}

$days = 166.0444;       
$datetime = convertDaysToDateTime($days, date('Y'));

echo $datetime->format('U = Y-m-d H:i:s');

答案 1 :(得分:1)

如果是当年,你可以

$days = 166.0444;
$date = new DateTime();
$date->setDate($date->format('Y'), 1, 1);
$date->add(new DateInterval('P' . floor($days) . 'D'));