Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get the first and last day of a month

Short answer

The modify() method understands the first day of and last day of expressions:

<?php
 
$date = new DateTimeImmutable('2026-02-14');
 
echo $date->modify('first day of this month')->format('Y-m-d'), ' ';
echo $date->modify('last day of this month')->format('Y-m-d');

Output:

2026-02-01 2026-02-28

How many days in a month

The t character in a date format is the number of days in the month:

<?php
 
echo (new DateTimeImmutable('2024-02-01'))->format('t'), ' ';
echo (new DateTimeImmutable('2026-02-01'))->format('t');

Output:

29 28

The next month

Do not add +1 month to a date at the end of a month — 31 January turns into early March. Use first day of next month:

<?php
 
$date = new DateTimeImmutable('2026-01-31');
 
echo $date->modify('+1 month')->format('Y-m-d'), ' ';
echo $date->modify('first day of next month')->format('Y-m-d');

Output:

2026-03-03 2026-02-01

Functions used in this recipe

  • DateTimeImmutable — A date and time object that cannot be changed: every operation returns a new object.
  • date — Formats a date and time.
  • strtotime — Turns a textual date description into a timestamp.

Thanks for reading!

Donate to the site — we work hard for you.