How to Get Current Month Using Date() Function in PHP

Subodh Poudel Feb 02, 2024
How to Get Current Month Using Date() Function in PHP

This tutorial introduces the way to find the current month in PHP.

Use the date() Function to Find the Current Month in PHP

We can use the date() function in PHP to get the current date according to the format provided. The syntax of the date() function is shown below.

date($format,$timestamp);

The $format option indicates the format of the date. We can set the format supported by the format() method of the DateTimeInterface class. The $format argument is a string. The $timestamp specifies the Unix timestamp, optional, and the date() function returns a string.

We can specify the various formats in the date() function to return the date according to our needs. We can return the current month of the year using such formats.

There are a list of format characters specified by DateTimeInterface::format() to set the date. Let’s explore some of the format characters that return the current month.

  • F: Returns the textual representation of the current month. For example, January.
  • m: It returns the numeric representation of the current month, with the prefix 0. For example, 01.
  • M: Returns the short textual representation of the current month. For example, Jan.
  • n: It returns the numeric representation of the current month without the prefix 0. For example, 1.

We will now implement the following format character for returning the current month.

For example, write the date() function and use the format characters mentioned above as the parameter to the function.

Do not forget to wrap the format characters with the quote and use the echo statement to print the function.

The current month of the year is February, and we can see the current month is displayed in the output section below. In this way, we can use format characters to get the current month of the year in PHP.

Example Code:

echo date('m');
echo ": Using the `m` format"."";
echo date('F');
echo ": Using the `F` format"."";
echo date('M');
echo ": Using the `M` format"."";
echo date('n');
echo ": Using the `n` format"."";
?>

Output:

02: Using the `m` format
February: Using the `F` format
Feb: Using the `M` format
2: Using the `n` format
Subodh Poudel avatar Subodh Poudel avatar

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

LinkedIn

Related Article - PHP DateTime