Forum Moderators: coopster

Message Too Old, No Replies

dateadd ?

         

jackvull

1:45 pm on Apr 30, 2008 (gmt 0)

10+ Year Member



I need to take a month of the current month in PHP and I have tried using mktime but doesn't seem to work?
Any ideas?

$date = date ( 'F' );
// - 1 month from today
echo date("F", mktime (0,0,0,-2,0,0,0));
echo date ( 'F', strtotime ( '-1 month' . $date ) );

The strtotime works but apparently is incorrect as it's only 30 days. Also, I nned to have -2 month all the way through to plus2 months as well...

jackvull

1:53 pm on Apr 30, 2008 (gmt 0)

10+ Year Member



This seems to give me March even though I have put in -2 and it is now April:

echo date("F", mktime(0,0,0,date("m")-2,date("d"),date("Y")));

dreamcatcher

2:35 pm on Apr 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I need to take a month of the current month in PHP and I have tried using mktime but doesn't seem to work?
Any ideas?

I`ve read through a couple of times now jackvull and I`m not sure what you are trying to do. Can you give us more information?

dc

jackvull

2:38 pm on Apr 30, 2008 (gmt 0)

10+ Year Member



Current mont is April
$date = date ( 'F' );

I need to find out programatically what the the previous 2 months were and the following 2 months so I can dipslay these in the page, e.g. February, March, April, May, June

OutdoorWebcams

2:58 pm on Apr 30, 2008 (gmt 0)

10+ Year Member



Substracting two months from the current date would lead to Feb. 30, which is correctly translated into March, 1st.
(Substracting one day from the current date: date("F", mktime(0,0,0,date("m")-2,date("d")-1,date("Y"))) gives the correct result, as this leads to Feb. 29th.)

To avoid this, you should substract three days from the current date if the day of the month is greater than 28 (to avoid even confusion during Feb/March change as in this example).

coopster

3:11 pm on Apr 30, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Easiest way to do these is to set the date to the first of the current month. For example:
// Grab the current month and year 
list($month, $year) = explode('-', date('m-Y'));
// Set the date to the first day of this month
$first = mktime(0, 0, 0, $month, 1, $year);
// We want to grab 2 months past, 2 months future
foreach (range(-2, 2) as $n) {
$n = ($n >= 0) ? "+$n" : $n;
print strftime('%B', strtotime("$n month", $first)) . "\n";
}