Skip to content

Instantly share code, notes, and snippets.

@diter14
Last active September 7, 2018 14:16
Show Gist options
  • Select an option

  • Save diter14/e0d704d2e518f8dd9a8f7164a286bf7b to your computer and use it in GitHub Desktop.

Select an option

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*
````php
// 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*
````php
$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
````php
$lastDayOfCurrentMonth = date('Y-m-t');
````
* How to get the last day of the previous month (and *n* months)
````php
$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