如何使用PHP获取当前月份和前三个月
有人会告诉我如何使用PHP获取当前月份和前三个月吗?
例如:
echo date("y:M:d");
输出将是: 09:10月:20
但我需要:
八月
九月
十月
作为输出。
提前致谢...
费罗
有人会告诉我如何使用PHP获取当前月份和前三个月吗?
例如:
echo date("y:M:d");
输出将是: 09:10月:20
但我需要:
八月
九月
十月
作为输出。
提前致谢...
费罗
对于月份的全文表示,您需要传递“F”:
echo date("y:F:d");
对于上个月,您可以使用
echo date("y:F:d",strtotime("-1 Months"))
;
当心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>";
欲了解更多信息,请参阅我的答案 请点击此处