是否有人告诉我如何使用PHP获取当前月份和前三个月
例如:
echo date("y:M:d");
输出将是:09:10月:20
但我需要:
八月
九月
十月
作为输出。
提前致谢...
FERO
答案 0 :(得分:24)
表示您需要传递“F”的月份的全文表示:
echo date("y:F:d");
上个月你可以使用
echo date("y:F:d",strtotime("-1 Months"))
;
答案 1 :(得分:14)
留意FUAH!其他答案将在本月31日执行时失败。请改用:
/*
Handles month/year increment calculations in a safe way,
avoiding the pitfall of 'fuzzy' month units.
Returns a DateTime object with incremented month values, and a date value == 1.
*/
function incrementDate($startDate, $monthIncrement = 0) {
$startingTimeStamp = $startDate->getTimestamp();
// Get the month value of the given date:
$monthString = date('Y-m', $startingTimeStamp);
// Create a date string corresponding to the 1st of the give month,
// making it safe for monthly calculations:
$safeDateString = "first day of $monthString";
// Increment date by given month increments:
$incrementedDateString = "$safeDateString $monthIncrement month";
$newTimeStamp = strtotime($incrementedDateString);
$newDate = DateTime::createFromFormat('U', $newTimeStamp);
return $newDate;
}
$currentDate = new DateTime();
$oneMonthAgo = incrementDate($currentDate, -1);
$twoMonthsAgo = incrementDate($currentDate, -2);
$threeMonthsAgo = incrementDate($currentDate, -3);
echo "THIS: ".$currentDate->format('F Y') . "<br>";
echo "1 AGO: ".$oneMonthAgo->format('F Y') . "<br>";
echo "2 AGO: ".$twoMonthsAgo->format('F Y') . "<br>";
echo "3 AGO: ".$threeMonthsAgo->format('F Y') . "<br>";
有关详情,请参阅我的回答here
答案 2 :(得分:6)
本月
date("y:M:d", mktime(0, 0, 0, date('m'), date('d'), date('Y')));
前几个月
date("y:M:d", mktime(0, 0, 0, date('m') - 1, date('d'), date('Y')));
date("y:M:d", mktime(0, 0, 0, date('m') - 2, date('d'), date('Y')));
答案 3 :(得分:2)
尝试在PHP中使用内置的strtotime
函数,并使用“F”进行全文输出:
echo date('y:F:d'); // first month
echo date('y:F:d', strtotime('-1 month')); // previous month
echo date('y:F:d', strtotime('-2 month')); // second previous month
echo date('y:F:d', strtotime('-3 month')); // third previous month
答案 4 :(得分:2)
如果你想成为OOP,试试这个:
$dp=new DatePeriod(date_create(),DateInterval::createFromDateString('last month'),2);
foreach($dp as $dt) echo $dt->format("y:M:d"),"\n"; //or "y F d"
输出:
答案 5 :(得分:0)
你需要使用日期(“F”);获取日期的全文表示。
答案 6 :(得分:0)
DECLARE @STARTDATE INT
SET @STARTDATE = -12
WHILE @STARTDATE < 0
BEGIN
PRINT DATENAME(MONTH,DATEADD(MM,@STARTDATE,GETDATE()))+' '+ DATENAME(YEAR, DATEADD(MM,@STARTDATE ,GETDATE()))
SET @STARTDATE =@STARTDATE+1
END
答案 7 :(得分:-1)
echo date('F', strtotime('-2 month')), '<br>',
date('F', strtotime('last month')), '<br>',
date('F');
答案 8 :(得分:-4)
DECLARE @STARTDATE VARCHAR(MAX)
DECLARE @ENDDATE VARCHAR(MAX)
DECLARE @A INT
SET @A=-12
SET @STARTDATE= DATENAME(MONTH,GETDATE())+ DATENAME(YEAR, DATEADD(MONTH,0,GETDATE()))
WHILE @A < 0
BEGIN
SET @STARTDATE = DATENAME(MONTH,DATEADD(MONTH,@A,GETDATE()))+' '+ DATENAME(YEAR, DATEADD(MONTH,@A,GETDATE()))
SET @A=@A+1
PRINT @STARTDATE
END