[英]how to get the previous 3 months in php
如何在php ex中獲取前3個月(如果我說DEC ..它應該顯示前3個月,即OCT NOV DEC)
您可以像這樣使用strtotime
函數:
echo date('M', strtotime('-3 month'));
所以你用減號指定以前的日期。
echo date('M', strtotime('0 month'));
echo date('M', strtotime('-1 month'));
echo date('M', strtotime('-2 month'));
echo date('M', strtotime('-3 month'));
結果:
Dec
Nov
Oct
Sep
如果您使用這樣的循環,您也可以這樣做:
for ($i = -3; $i <= 0; $i++){
echo date('M', strtotime("$i month"));
}
結果:
Sep
Oct
Nov
Dec
查看文檔也可以看到strtotime
支持的許多其他友好的日期和時間關鍵字:
投票的答案幾乎是正確的。
正確的解決辦法是:
for ($i = -3; $i <= 0; $i++){
echo date('M', strtotime("$i month", strtotime(date("Y-m-15"))));
}
說明: strtotime默認實現是:
date ( string $format [, int $timestamp = time() ] ) : string
如您所見,時間戳的默認值為:time()。
最后說今天是3月31日。
因為沒有2月31日
echo date('M', strtotime("-1 month"));
將返回三月
另一方面:
echo date('M', strtotime("+1 month"));
將返回五月(四月將被跳過)。
由於這個問題,我們必須設置時間戳值,這是一個安全的日期。 1-28 之間的每個日期都是安全的,因為每個月都有那個日期。 在我的例子中,我選擇了一個月的第 15 天。
這可能會幫助你`
<?php
$date = explode("-", "2016-08-31");
if($date[2]== "01"){$days = "-0 days";}else{$days = "-1 days";}
$time = strtotime($days, mktime(0, 0, 0, $date[1], $date[2], $date[0]));
$MTD = date('Y-m-01', strtotime('0 month'));
$M1 = date('Y-m-01', strtotime('-1 month'));
$M2 = date('Y-m-01', strtotime('-2 month'));
$M3 = date('Y-m-01', strtotime('-3 month'));
$rng = array();
$rng[$MTD] = strftime("%B, %Y", strtotime(" ", $time));
$rng[$M1] = strftime("%B, %Y", strtotime("first day of previous month", $time));
$rng[$M2] = strftime("%B, %Y", strtotime("-2 months", $time));
$rng[$M3] = strftime("%B, %Y", strtotime("-3 months", $time));
?>
這里 $MTD ,$M1,$M2,$M3 將以 "dd-mm-yyyy" 和 $rng[$MTD], $rng[$M1],$rng[$M2],$rng 的形式給出日期[$M3] 以“月份名稱,年份”=> 的形式給出日期(即 2016 年 8 月)
$month = date('M');
$year = date('Y');
$no_of_mnths = date('n',strtotime("-2 months"));
$remaining_months = (12 - $no_of_mnths)."\r\n";
$tot = $remaining_months+1;
for($j=0;$j<$tot;$j++){
echo date('M',strtotime(''.$no_of_mnths.' months'))
$no_of_mnths++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.