Open In App

How to Get Number of Days in Current Month in PHP?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

This article will show you how to get the number of days in the current month in PHP. In PHP, you may need to find the number of days in the current month for various purposes, such as generating a calendar or performing date calculations. There are three approaches to get the number of days in the current month, these are described below:

Approach 1: Using cal_days_in_month() Function

The cal_days_in_month() function is a basic method to get the number of days in a specific month.

PHP
<?php
  
$year = date("2024");
$month = date("4");
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);

echo "Number of days in the current month: $days";
?>

Output

Number of days in the current month: 30

Explanation:

  • date(“Y”) and date(“n”): These functions return the current year and month, respectively.
  • cal_days_in_month(): This function takes three arguments: the calendar type (Gregorian in this case), the month, and the year. It returns the number of days in the specified month.

Approach 2: Using date() and strtotime() Functions

Another approach is to use the date() function in combination with strtotime() to calculate the number of days in the current month.

PHP
<?php

$monthFirstDay = date("2024-4-01");
$monthLastDay = date(
    "2024-4-30", 
    strtotime($monthFirstDay)
);

$days = date("d", strtotime($monthLastDay));

echo "Number of days in the current month: $days";

?>

Output
Number of days in the current month: 30

Explanation:

  • date(“Y-m-01”): This gets the first day of the current month.
  • date(“Y-m-t”, strtotime($firstDayOfMonth)): This gets the last day of the current month using the t format character, which represents the number of days in the given month.
  • date(“d”, strtotime($lastDayOfMonth)): This extracts the day number from the last day of the month, which is the total number of days in the month.

Approach 3: Using DateTime Objects

You can also use PHP’s DateTime class to get the number of days in the current month.

PHP
<?php

$date = new DateTime();
$days = $date->format('t');

echo "Number of days in the current month: $days";

?>

Output
Number of days in the current month: 30

Explanation:

  • new DateTime(): This creates a DateTime object representing the current date.
  • $date->format(‘t’): This formats the date to return the number of days in the current month.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads