Page 1 of 1

last month

Posted: Tue Jan 15, 2008 9:30 am
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

Re: last month

Posted: Tue Jan 15, 2008 9:50 am
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;
  
?>
 

Re: last month

Posted: Tue Jan 15, 2008 10:27 am
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")));

Re: last month

Posted: Tue Jan 15, 2008 1:26 pm
by RobertGonzalez

Code: Select all

<?php
$last = date('m/Y', strtotime('last month'));
?>

Re: last month

Posted: Tue Jan 15, 2008 1:40 pm
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

Re: last month

Posted: Tue Jan 15, 2008 1:47 pm
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).