Andrew
Andrew

Reputation: 7

Date offset in PHP

I am doing my own calendar. For changing to the next and previous months, I use this function:

date('m',"-1 months");
date('m',"+1 months");

but, when I go to the next month, I can't use this again because -1 and +1 are always taken from now().

Assuming that I can't use dynamic numbers to that offset, I mean

date('m',"$x months");

how can I add or subtract 1 month to a specific date?

For example this date...

$date_today = strtotime($_GET['date']);
$next_month = $date_today +/- 1 month ?!?!??! 

Upvotes: 0

Views: 818

Answers (4)

James Williams
James Williams

Reputation: 4216

I currently run a calendar for multiple sites with the same issue. I end up storing the current viewable month as a $_SESSION variable or pass it as a $_POST object when someone clicks on next or prev month.

When you would call it when the next or prev was hit a second time would (or the first time) would be something like

if(!isset($_SESSION['viewablemonth']) && $_SESSION['viewablemonth'] = '') {
    $_SESSION['viewablemonth'] = date("m.d.Y");
}

End then do your month addition or subtraction:

$_SESSION['viewablemonth'] = strtotime("+1 month", $_SESSION['viewablemonth']);

Upvotes: 1

Waygood
Waygood

Reputation: 2693

You can mix strtotimes up with a reference date so:

$next_month=strtotime("+1 month");  // assumes today
$following_month=strtotime("+1 month", $next_month);

http://uk.php.net/manual/en/function.strtotime.php Takes two parameters and assumes second parameter is time() current timestamp if ommitted

Upvotes: 0

RiaD
RiaD

Reputation: 47619

$next_month = strtotime('+1 month',$date_today);

Upvotes: 3

fire
fire

Reputation: 21531

Use strtotime...

$next_month = strtotime("+1 month");

Will give you a unix timestamp which you can pass to date...

echo date("m", $next_month);

Upvotes: 2

Related Questions