biy*_*ro2 1 php datetime datediff
我希望在两个日期之间的数组中依次获得所有月份和年份.我希望输出像这样的格式:Ym
我做完了.但是,我只是想知道是否有任何简单的方法来获得相同的结果.
有我的代码:
public function __construct()
{
$this->params['start-date'] = date('Y-m-d', strtotime("01-01-2016"));
$this->params['end-date'] = date('Y-m-d', time());
}
/**
* @return array
*/
private function _getAllMonths()
{
$start = date_parse($this->params["start-date"]);
$end = date_parse($this->params["end-date"]);
$output[] = ['month' => $start["year"]."-0".$start["month"]];
//loop years
for($i=(int)$start["year"];$i<=(int)$end["year"];$i++)
{
//control months and start year
$k = $i == $start["year"] ? (int)$start["month"] + 1 : 1;
//loop months
for($j=$k;$j<13;$j++)
{
if($i==$end["year"] && $j==$end["month"])
break;
$output[] = ["month" => $i."-".str_pad($j, 2, "0", STR_PAD_LEFT)];
}
}
return $output;
}
Run Code Online (Sandbox Code Playgroud)
请解释我怎么样?
怎么样才能让你入门
$start = new \DateTime('now');
$end = new \DateTime('now + 3 years');
$interval = new \DateInterval('P1M');
$period = new \DatePeriod($start, $interval, $end);
foreach($period as $date) {
echo $date->format('Y-m-d H:i:s') . "\n";
}
Run Code Online (Sandbox Code Playgroud)
不是一个很大的步骤来适应您的需求
PHP手册页
如果您在日期上做了很多,我建议使用名为Carbon的库
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |