Skip to content

Instantly share code, notes, and snippets.

@kingjmaningo
Last active May 20, 2020 02:37
Show Gist options
  • Save kingjmaningo/8c3b054949a01a30d168785f4f4d36dc to your computer and use it in GitHub Desktop.
Save kingjmaningo/8c3b054949a01a30d168785f4f4d36dc to your computer and use it in GitHub Desktop.
Get previous/next month php
<?php
// Number of months after/before
$num = 3;
// Months before
$now = new DateTime();
$lastMonth = $now->sub(new DateInterval('P'. $num . 'M'));
// displays month/s before
echo $lastMonth->format('Y M');
// quick and short way
echo date('M', strtotime("-". $num . " month"));
// Months after
$nextMonth = $now->add(new DateInterval('P'. $num . 'M'));
// displays month/s after
echo $nextMonth->format('Y m');
// quick and short way
echo date('M', strtotime("+". $num . " month"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment