How to Convert a Number to Month Name in PHP
-
Use the
DateTime
Object to Convert a Number to a Month Name in PHP -
Use the
mktime()
Function to Display Month Name in PHP -
Use the
strtotime()
Function to Display Month Name in PHP
As you write PHP applications, you will work with date and time. Working with these two is easy, especially with the different objects and functions available.
We can use these functions from the second, minute, hour, day, and month to a year. However, we want to create the month name from numbers or string date format in this article.
Use the DateTime
Object to Convert a Number to a Month Name in PHP
You can ensure the DateTime
object outputs the month name using the method, createFromFormat()
, which takes two arguments as in the code below. Afterward, you will use the format()
method on the DateTime
object.
The argument that the format()
method takes is the date format, and for the full textual representation of a month, it is the letter F
.
## Using DateTime Object
$monthNumber = 5;
$dateObject = DateTime::createFromFormat('!m', $monthNumber);
$monthName = $dateObject->format('F'); // March
echo $monthName;
Output:
May
Use the mktime()
Function to Display Month Name in PHP
The mktime()
function is an inbuilt function we can use to display the month name. Note that it can display other things from day to year.
We take the Unix timestamp; it returns and parses it to the date()
function to return a string that contains the month name. Also, we parse the letter F
to specify it is the month we need.
## mktime() functions - especially for older PHP, PHP 8.0 and below
// Declare month number and initialize it
$monthNumber = 6;
// Use mktime() and date() function to
// convert number to month name
$monthName = date("F", mktime(0, 0, 0, $monthNumber, 10));
// Display month name
echo $monthName;
Output:
June
Use the strtotime()
Function to Display Month Name in PHP
Similar to mktime()
, we can place the Unix Epoch timestamp and obtain the month name. The letter F
is the first argument we will pass to the date()
function.
## date() and strtotime() functions
echo date("F", strtotime('2022-06-05 11:22:51'));
Output:
June
Olorunfemi is a lover of technology and computers. In addition, I write technology and coding content for developers and hobbyists. When not working, I learn to design, among other things.
LinkedIn