How to usedate() and strtotime() Functions in PHP

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.

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

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:

Table of Content

  • Using cal_days_in_month() Function
  • Using date() and strtotime() Functions
  • Using DateTime Objects

Similar Reads

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....

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....

Approach 3: Using DateTime Objects

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