在php中将天转换为月和日

  • 本文关键字:转换 php php
  • 更新时间 :
  • 英文 :


我有一个数字144,我想转换成月和日,即我想显示3个月24天。

做这个的公式是什么?我已经尝试了许多方法,但都没有用。

$sub_struct_month = ($result[0] / 30) ;
$sub_struct_month = floor($sub_struct_month); 
$sub_struct_days = ($result[0] / 30); // the rest of days
$sub_struct = $sub_struct_month."m ".$sub_struct_days."d";

使用模数运算符获得正确的天数:

<?php
$result = array(144);
$sub_struct_month = ($result[0] / 30) ;
$sub_struct_month = floor($sub_struct_month); 
$sub_struct_days = ($result[0] % 30); // the rest of days
$sub_struct = $sub_struct_month."m ".$sub_struct_days."d";
echo $sub_struct;
?>

4m 24d .

详细信息:http://php.net/manual/en/language.operators.arithmetic.php

你知道有闰年(二月有时有29天)吗?比如七月和八月有31天。你一般不能说"把144天转换成月",因为每个月都不一样。

<?php
$start_date = new DateTime(date("Y/m/d"));
$end_date = new DateTime(date("Y/m/d",strtotime("+144 days")));
$dd = date_diff($start_date,$end_date);
echo "$dd->m months $dd->d days";
?>

对于start_date你可以使用一个特定的日期!同样用于end_date这是正确的方法,所以每一个闰年和一切都被观察到!

PHP有一个完美的类来处理日期:DateTime

这个类允许你获得两个日期之间的差异DateTime::diff和格式化结果,如你想使用DateTime::format

是的,这不是你想要的。但是它允许你得到精确的日期和月份值。

所以,我建议你先阅读文档。我希望你能找到一种方法如何在你的情况下实现它。

请尝试下面的代码

  $months = floor(144 / 30);
  $days = 144 - ($months*30);
  echo  $months ."Months " . $days ."days";

我的做法

$days = 144;
$month = $days/30;
list($month,$days) = explode(".",$month);
$days = "0.".$days;
echo $month."</br>";
echo $days*30;

最新更新