Skip to content

Instantly share code, notes, and snippets.

@diter14
Last active September 7, 2018 14:16
Show Gist options
  • Save diter14/e0d704d2e518f8dd9a8f7164a286bf7b to your computer and use it in GitHub Desktop.
Save diter14/e0d704d2e518f8dd9a8f7164a286bf7b to your computer and use it in GitHub Desktop.
How to add or subtract dates in PHP

How to add or subtract dates in PHP

  • For current date
// You can add or subtract days, weeks, months, years using
// (+/-)(number) (day|week|month|year)
// e.g. "+1 year"

$currentDate = date('Y-m-d');
// Print: 2018-09-06
$currentDateMinusOneMonth = date('Y-m-d', strtotime('-1 month', strtotime($currentDate)));
// Print: 2018-08-06
  • For specific dates
$specificDate = strtotime('2000-01-01');
$specificDateMinusOneWeek = date('Y-m-d', strtotime("-1 week", $specificDate));
// Print: 1999-12-25
  • Tips

    • How to get the last day of the current month

      $lastDayOfCurrentMonth = date('Y-m-t');
    • How to get the last day of the previous month (and n months)

      $lastDayOfPreviousMonth = date('Y-m-t', strtotime('-1 month',strtotime(date('Y-m'))));
      $lastDayOfNPreviousMonth = date('Y-m-t', strtotime('-n month',strtotime(date('Y-m'))));
      // n: any number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment