首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用PHP获取当月和前三个月

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

Stack Overflow用户
提问于 2009-10-20 12:32:29
回答 8查看 64.5K关注 0票数 20

谁能告诉我如何使用PHP获取当月和前三个月

例如:

代码语言:javascript
复制
echo date("y:M:d");

输出将为: 09:Oct:20

但我需要:

八月

九月

十月

作为输出。

先谢谢你...

费罗

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2009-10-20 12:36:18

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

代码语言:javascript
复制
echo date("y:F:d");

对于上个月,您可以使用

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

票数 30
EN

Stack Overflow用户

发布于 2010-11-28 04:18:02

当心FUAH!其他答案在该月31号执行时将失败。改用下面的代码:

代码语言:javascript
复制
/*
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

票数 14
EN

Stack Overflow用户

发布于 2009-10-20 12:36:47

这个月

代码语言:javascript
复制
date("y:M:d", mktime(0, 0, 0, date('m'), date('d'), date('Y')));

前几个月

代码语言:javascript
复制
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')));
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1594277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档