Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert number to month name in PHP?
In PHP, you can convert a month number to its corresponding month name using several built-in functions. The most common approaches are using date() with mktime() or the DateTime class.
Using date() with mktime()
The mktime() function creates a timestamp, which can then be formatted using date() to get the month name ?
<?php
$month_number = 11;
echo "Month number: $month_number
";
// Convert month number to full month name
$month_name = date("F", mktime(0, 0, 0, $month_number, 1));
echo "Full month name: $month_name
";
// Convert to short month name
$short_month = date("M", mktime(0, 0, 0, $month_number, 1));
echo "Short month name: $short_month
";
?>
Month number: 11 Full month name: November Short month name: Nov
Using DateTime Class
The DateTime class provides a more object-oriented approach for month conversion ?
<?php
$month_number = 12;
echo "Month number: $month_number
";
// Create DateTime object from month number
$date_obj = DateTime::createFromFormat('!m', $month_number);
// Get full month name
$full_name = $date_obj->format('F');
echo "Full month name: $full_name
";
// Get short month name
$short_name = $date_obj->format('M');
echo "Short month name: $short_name
";
?>
Month number: 12 Full month name: December Short month name: Dec
Converting from Date String
You can also extract the month name from a complete date string ?
<?php
$date_string = "2019-11-15";
echo "Date: $date_string
";
// Extract month name from date string
$month_name = date("F", strtotime($date_string));
echo "Month name: $month_name
";
// Alternative using DateTime
$date_obj = new DateTime($date_string);
$month_alt = $date_obj->format('F');
echo "Month (alternative): $month_alt
";
?>
Date: 2019-11-15 Month name: November Month (alternative): November
Conclusion
Use date("F", mktime(0, 0, 0, $month_number, 1)) for a simple conversion or DateTime::createFromFormat('!m', $month_number) for object-oriented approach. Both methods support full ("F") and abbreviated ("M") month names.
Advertisements
