last month

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
jamiller
Forum Commoner
Posts: 26
Joined: Mon Mar 12, 2007 12:25 pm

last month

Post by jamiller »

Hello all, I'm building a calendar with PHP and I'm trying to find out how to successfully obtain a value for last month in a m/Y format. So if $today = date("m/Y") or 01/2008 then last month should be 12/2007. I've tried everything but no luck. And in case you haven't already figured it out, I'm not exactly an expert with PHP - yet.

Thanks for any and all help!

Jeff
User avatar
jimthunderbird
Forum Contributor
Posts: 147
Joined: Tue Jul 04, 2006 3:59 am
Location: San Francisco, CA

Re: last month

Post by jimthunderbird »

For your reference and for my coding breakfast :D

Code: Select all

 
<?php
  $cur_time = time();
  $cur_time_format = date("m/Y",$cur_time);
  $cur_time_format_explodes = explode("/",$cur_time_format);
  
  $cur_month = (int)$cur_time_format_explodes[0];
  $cur_year = (int)$cur_time_format_explodes[1];
  
  $last_month = $cur_month - 1;
  
  if($last_month == 0){
    $cur_year = $cur_year - 1;
    $last_month = 12;
  }
  
  $last_month = str_pad($last_month,2,0,STR_PAD_LEFT);
  $last_month_format = $last_month."/".$cur_year;
  
  print $last_month_format;
  
?>
 
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: last month

Post by VladSun »

From the examples in http://bg.php.net/manual/en/function.date.php

Code: Select all

date('m/Y', mktime(0, 0, 0, date("m")-1, date("d"),   date("Y")));
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: last month

Post by RobertGonzalez »

Code: Select all

<?php
$last = date('m/Y', strtotime('last month'));
?>
User avatar
jimthunderbird
Forum Contributor
Posts: 147
Joined: Tue Jul 04, 2006 3:59 am
Location: San Francisco, CA

Re: last month

Post by jimthunderbird »

Everah wrote:

Code: Select all

<?php
$last = date('m/Y', strtotime('last month'));
?>
Wow Everah, you solution is elegant! I learned something new, thanks :D
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: last month

Post by RobertGonzalez »

Play with that code a little bit. I didn't test it. It could go wobbly on you if your default timezone is not set (as well as the slough of other things that could go wobbly with strtotime).
Post Reply