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.

Revisions

  1. diter14 renamed this gist Sep 6, 2018. 1 changed file with 0 additions and 0 deletions.
  2. diter14 created this gist Sep 6, 2018.
    40 changes: 40 additions & 0 deletions How to handle dates in PHP
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    # 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
    ````