PHP Date Exercises : Get the first and last day of a month from a specified date
PHP date: Exercise-8 with Solution
Write a PHP script to get the first and last day of a month from a specified date.
Sample Solution:
PHP Code:
<?php
$dt = "2008-02-23"; // Define the date string
echo 'First day : '. date("Y-m-01", strtotime($dt)).' - Last day : '. date("Y-m-t", strtotime($dt));
?>
Output:
First day : 2008-02-01 - Last day : 2008-02-29
Explanation:
In the exercise above,
- $dt = "2008-02-23";: Specifies the date string "2008-02-23".
- strtotime($dt): Converts the date string to a Unix timestamp.
- date("Y-m-01", strtotime($dt)): Formats the Unix timestamp to display the first day of the month in the format "YYYY-MM-01".
- date("Y-m-t", strtotime($dt)): Formats the Unix timestamp to display the last day of the month in the format "YYYY-MM-t", where "t" represents the number of days in the given month.
- echo 'First day : '. date("Y-m-01", strtotime($dt)).' - Last day : '. date("Y-m-t", strtotime($dt));: Prints the formatted first and last days of the month.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to calculate number of days between two dates.
Next: Write a PHP script to print like : Saturday the 7th
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/php-exercises/php-date-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics