简体   繁体   English

使用php从当前月份获取最近3个月

[英]get last 3 months from current month using php

I want to get last 3 months name from current month. 我想从当前月份获得最近3个月的名字。 For example current month is August. 例如,当前月份是八月。 So, I want the datas like these June, July, August. 所以,我想要像六月,七月,八月这样的数据。 I have tried this code echo date("F", strtotime("-3 months")); 我已经尝试过此代码echo date("F", strtotime("-3 months")); . it returns June only. 它仅返回六月。 How do I get last 3 months from current month using php? 我如何使用php从当前月份获得最近3个月?

Simple code: 简单的代码:

<?php

for($x=2; $x>=0;$x--){
echo date('F', strtotime(date('Y-m')." -" . $x . " month"));
echo "<br>";
}

?>

Got the idea from LTroubs here . 从LTroubs 那里得到了这个想法。

That should work: 那应该工作:

function lastThreeMonths() {
    return array(
        date('F', time()),
        date('F', strtotime('-1 month')),
        date('F', strtotime('-2 month'))
    );
}

var_dump(lastThreeMonths());

You are actually on the right track by using date and strtotime functions. 通过使用日期和strtotime函数,您实际上在正确的轨道上。 Expanding it below to your requirements: 在下面将其扩展为您的要求:

function getMonthStr($offset)
{
    return date("F", strtotime("$offset months"));
}

$months = array_map('getMonthStr', range(-3,-1));

Try this:- 尝试这个:-

$current_date = date('F');
for($i=1;$i<3;$i++)
{
    ${"prev_mont" . $i} = date('F',strtotime("-$i Months"));
    echo ${"prev_mont" . $i}."</br>";
}
echo $current_date."</br>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM