How to Get Last Day/date of the Current Month in PHP?

Problem:

You want to find the last date of the current month.

Solution:

There are few ways you can use to get the last day of the current month. Let’s see how these work.

Method 1: Using date() function

The example below is the simplest way to find out the last day of the current month.

<?php
echo date("m-t-Y");
?>

[wpdm_file id=112]

Output:
05-31-2014

How it works:
date() function returns a formatted date string according to the format given as the parameter. In the above example, the formatting characters are “m-t-Y”. Here, m is used to display month as number with leading zero. As this is May, the output display 05. t helps to display number of days of the current month. In May, there are 31 days which is displayed in the output. At last, Y displays the year in four digits.

 

Method 2: Using strtotime() function

strtotime() function can convert predefined date time strings to their equivalent timestamps. These date time strings must follow some predefined formats. One of the supported formats is relative formats which we’ll use to define the last date of the current month. The following example shows how it works-

<?php
$timestamp = strtotime("last day of");
echo date("m-d-Y", $timestamp);
?>

[wpdm_file id=111]

Output:
05-31-2014

How it works:
The formatting parameter “last day of” which sets the last date of the current month is created from a relative formats.

 

Method 3: Using the modify() method of DateTime class from SPL

Using the modify() methods, we can find the last date of the current month in the following example-

<?php
$dateObj = new DateTime('2014-05-26');
$dateObj->modify(last day of');
echo $dateObj ->format('m-d-Y');
?>

[wpdm_file id=113]

Output:
05-31-2014

How it works:

Line 2 It creates a new DateTIme object($dateObj) with the current date.
Line 3 The modify() method alters the date (which is existed as the DateTime object it uses) to the last date of the month of that date(2014-05-26). Here, the formatting parameter “last day of” sets the last date of the current month. It is the same date time formats that strtotime() function allows. See other date time format that modify() method allows. The modify() method returns the altered DateTIme object.
Line 4 The format() method format the DateTime object according to the format mentioned in its parameter and returns it. And, it is the output you see.