w3resource

PHP Date Exercises : Get the first and last day of a month from a specified date


8. First and Last Day of Month

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 :

Flowchart: Get the first and last day of a month from a specified date

For more Practice: Solve these Related Problems:

  • Write a PHP script to retrieve the first and last day of the month for a given input date using DateTime and modify date formats.
  • Write a PHP function that calculates the first and last days for any month and outputs them as an associative array.
  • Write a PHP program to print the first and last days of the current month, then display the same for the next month.
  • Write a PHP script to create a function that takes a date as input and returns the first Monday and the last Friday of that month.

Go to:


PREV : Calculate Days Between Two Dates.
NEXT : Display Date in "Saturday the 7th" Format.

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.



Follow us on Facebook and Twitter for latest update.