给定 PHP 中的天数,如何从中计算年、月和日?

Given the number of days in PHP, how do I calculate years, months, and days from it?

我将天数存储在 Mysql 数据库中,我正在尝试将这些天数格式化为年、月、日格式。我存储日期的变量称为 $days

这是我的资料:

$years = ($days / 365);
$years = floor($years);

$month = ($days % 365) / 30.5;
$month = floor($month);

$days = ($days % 365) % 30.5;

$display = "$years" . " years, " . "$month" . " months, and " . "$days" . " days";

但是,每当我将天数设置为 90 之类的值时,它只会显示 2 个月,而不会显示任何天数,只有 2 个月。我在某个地方在网上找到了这个,直到最近它都运行良好。

任何人都可以就更好的方法或我的代码中的任何错误向我提供一些指导吗?

像下面那样做:-

<?php
  $days = '365';
  $start_date = new DateTime(date("Y/m/d"));
  $end_date = new DateTime(date("Y/m/d",strtotime("+$days days")));
  $dd = date_diff($start_date,$end_date);
  echo "$dd->y year(s) $dd->m month(s) $dd->d day(s)";
?>

输出:- https://eval.in/918854 AND https://eval.in/918858

由于没有指定具体日期,您可以这样做

<?php
$days = 500;
$years = intval($days / 365); 
$days = $days % 365;

$months = intval($days / 30); 
$days = $days % 30;

echo "$years years, $months months, $days days";

?>

现场演示:https://eval.in/918861

输出如下:1 years, 4 months, 15 days