PHP Date Exercises : Convert the number to month name
26. Convert Number to Month Name
Write a PHP script to convert the number to month name.
Sample Solution:
PHP Code:
<?php
// Define the month number
$month_num = 9;
// Create a DateTime object from the month number
$dateObj = DateTime::createFromFormat('!m', $month_num);
// Format the DateTime object to retrieve the full month name
$month_name = $dateObj->format('F');
// Output the full month name
echo $month_name."\n";
?>
Output:
September
Explanation:
In the exercise above,
- $month_num = 9;: Assigns the month number (in this case, September, represented by 9) to the variable '$month_num'.
- $dateObj = DateTime::createFromFormat('!m', $month_num);: Creates a "DateTime" object using the DateTime::createFromFormat() method. The '!m' format string specifies that the input is a month number. It converts the month number into a "DateTime" object.
- $month_name = $dateObj->format('F');: Formats the "DateTime" object to retrieve the full month name using the "format()" method with the format specifier 'F', which represents the full textual representation of a month.
- echo $month_name."\n";: Outputs the full month name followed by a newline character.
Flowchart :
For more Practice: Solve these Related Problems:
- Write a PHP function to convert a given month number to its full month name using a switch or associative array.
- Write a PHP script to output the month name in both English and another language, based on a numeric input.
- Write a PHP program to accept a numeric month and return its abbreviated name, ensuring correct handling of edge values.
- Write a PHP script to map month numbers to names and then format a date string by replacing the numeric month with its name.
Go to:
PREV : Current Date in Italian.
NEXT : Days in Current Month.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.