w3resource

PHP Date Exercises : Convert the number to month name

PHP date: Exercise-26 with Solution

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 :

Flowchart: Convert the number to month name

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to get the current date in Italian.
Next: Write a PHP script to get the number of days of the current month.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-date-exercise-26.php