tags:

views:

481

answers:

6

Hi all

Will any one tell me how to get the current month and previous three months using PHP

For example:

echo date("y:M:d");

output will be: 09:Oct:20

But i need:

August

September

October

as the Output.

Thanks in advance...

Fero

A: 

You'll need to use date("F"); to get the full text representation of the date.

somacore
+5  A: 

for full textual representation of month you need to pass "F":

echo date("y:F:d");

for previous month you can use

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

Deniss Kozlovs
thanks tyler.. i need this one...
Fero
+5  A: 

this month

date("y:M:d", mktime(0, 0, 0, date('m'), date('d'), date('Y')));

previous months

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')));
martin.malek
yours this answer produces PARSE ERRORParse error: syntax error, unexpected ';' in E:\Program Files\xampp\htdocs\test_Fero\test.php on line 3
Fero
If you count the opening-brackets `(` you'll find there are five in each line, but only four closing-brackets. If you balance the two, five of each, the code should work.
David Thomas
Looks like you need another closing ")" before the semicolon.
Eric Petroelje
@Fero add an extra ')' at the end of the lines before the semicolons.
richsage
A: 

Try using the built in strtotime function in PHP and using 'F' for full textual output:

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
Nathan Kleyn
A: 
echo date('F', strtotime('-2 month')), '<br>',
     date('F', strtotime('last month')), '<br>',
     date('F');
vava
Remembering that "last" is simply a synonym for "-1", you should not double up on strtotime()'s when not necessary; this is just wasting cycles.
Nathan Kleyn
What's wrong with it? It's working as required :)
vava
@Nathan Kleyn, I didn't about "-1 month" syntax, "last month" was just a guess that worked.
vava
A: 

If you want to be OOP about it, try this:

$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"

outputs:

  • 09:Oct:20
  • 09:Sep:20
  • 09:Aug:20
dnagirl