How to Get Last Day of Month from Date in PHP - TechvBlogs
PHP

How to Get Last Day of Month from Date in PHP

In this article, You will learn How to Get Last Day of Month from Date in PHP.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

1 month ago

TechvBlogs - Google News

When faced with the task of printing the final day of a given month in PHP, you can achieve this by utilizing the date() and strtotime() functions. Employing these functions allows for a seamless retrieval of the last day of the month based on a provided date.

Used PHP functions:

  • The date() function in PHP is utilized to format a local time or date according to specified parameters.

  • The strtotime() function in PHP is employed to parse nearly any English textual datetime description and convert it into a Unix timestamp.

Examples:

Input: 2020-04-23
Output: Thursday

Input: '2018-09-11'
Output: Sunday

Approach:

  • When provided with a date stored as a string in a variable, the process involves converting it into a date format using the strtotime() function.
  • After obtaining the date, we will utilize the date() method.

           Syntax:

           date( $format, $timestamp )

  • Within the $format, we will pass 'Y-m-t', and within $timestamp, the date obtained earlier. In terms of the date format, 'Y' represents a full numeric representation of a year in four digits, 'm' provides a numeric representation of a month, and 't' gives the number of days in the given month.
  • Utilizing 'Y-m-t', we can retrieve the number of days in a month, as 't', 'm', and 'Y' respectively represent the day, month, and year components of the date.
  • The final step involves once again using the date() function, this time with 'l' as the format, and the previously obtained date as the $timestamp.
  • Display the day.

Program:

<?php 
   
// Given a date in string format  
$datestring = '2020-04-23'; 
  
// Converting string to date 
$date = strtotime($datestring); 
   
// Last date of current month. 
$lastdate = strtotime(date("Y-m-t", $date )); 

// Day of the last date  
$day = date("l", $lastdate); 
  
echo $day; 
?> 

Output:

Thursday

I'm here to help! If you have any more questions or if there's anything else I can assist you with, feel free to let me know.

Comments (0)

Comment


Note: All Input Fields are required.