php get last day of month | php get first and last day of last month | php get last day of month | get first and last day of month php

How can I get last day of the month in PHP?

I assume you need to get the last day of the month in PHP. Don’t worry-you would find this post helpful.

Let me make clear the first argument of the PHP date function is a format and accepts only DateTimeInterface::format().

Generally, it is like a ‘Y-m-d’ like format.

<?php echo date('Y-m-d'); ?>

It gave the current date.

But there is a “t” that returns the number of days on a given date. Moreover, this can be useful to find the last day of the month.

To find the last day of the current month

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

To find the last day of a specific date

<?php 
	$a_date = "2021-09-05";
	echo date("Y-m-t", strtotime($a_date));
?>

The above code would output 2021-09-30. As we can see we have to convert the given date to an int Unix timestamp, Which is the second argument of the date function.

But due to server architecture like the 32-bit version of PHP, it can show some strange behavior, Instead of strtotime, We can use the DateTime function.

Using the DateTime function.

With DateTime() function you can do something like this:

<?php
   print_r( (new DateTime('2021-09-05'))->modify('last day of'));
?>
DateTime Object
(
    [date] => 2021-09-30 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)

Find first day of month

<?php
	print_r( (new DateTime('2021-09-05'))->modify('first day of'));
?>

Find first and last day of last month

<?php
	print_r( (new DateTime('2021-09-05'))->modify('first day of last month'));
	print_r( (new DateTime('2021-09-05'))->modify('last day of last month'));
?>

Check How to display category name in WordPress.

Leave a Comment

Your email address will not be published. Required fields are marked *