如何使用PHP获取当前月份和前三个月

Fer*_*ero 19 php date

有人会告诉我如何使用PHP获取当前月份和前三个月

例如:

echo date("y:M:d");
Run Code Online (Sandbox Code Playgroud)

输出将是:09:10月:20

但是我需要:

八月

九月

十月

作为输出.

提前致谢...

FERO

Den*_*ovs 26

对于月份的全文表示,您需要传递"F":

echo date("y:F:d");
Run Code Online (Sandbox Code Playgroud)

对于上个月你可以使用

echo date("y:F:d",strtotime("-1 Months"));

  • 这将在31日执行时失败.看我的回答. (4认同)

Yar*_*rin 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>";
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此处的答案


mar*_*lek 6

这个月

date("y:M:d", mktime(0, 0, 0, date('m'), date('d'), date('Y')));
Run Code Online (Sandbox Code Playgroud)

前几个月

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')));
Run Code Online (Sandbox Code Playgroud)