The first day of the current month in php using date_modify as DateTime object


Question

I can get the Monday of this week with:

$monday = date_create()->modify('this Monday');

I would like to get with the same ease the 1st of this month. How can I achieve that?

1
141
3/14/2019 6:55:15 AM

Accepted Answer

Requires PHP 5.3 to work ("first day of" is introduced in PHP 5.3). Otherwise the example above is the only way to do it:

<?php
    // First day of this month
    $d = new DateTime('first day of this month');
    echo $d->format('jS, F Y');

    // First day of a specific month
    $d = new DateTime('2010-01-19');
    $d->modify('first day of this month');
    echo $d->format('jS, F Y');

    // alternatively...
    echo date_create('2010-01-19')
      ->modify('first day of this month')
      ->format('jS, F Y');

In PHP 5.4+ you can do this:

<?php
    // First day of this month
    echo (new DateTime('first day of this month'))->format('jS, F Y');

    echo (new DateTime('2010-01-19'))
      ->modify('first day of this month')
      ->format('jS, F Y');

If you prefer a concise way to do this, and already have the year and month in numerical values, you can use date():

<?php
    echo date('Y-m-01'); // first day of this month
    echo date("$year-$month-01"); // first day of a month chosen by you
232
3/18/2015 6:15:48 PM

Here is what I use.

First day of the month:

date('Y-m-01');

Last day of the month:

date('Y-m-t');

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon