Home > Article > Backend Development > How to Find the First and Last Days of a Month in PHP?
Determining Month's First and Last Dates in PHP
Finding the first and last dates of a specific month is a crucial task in various applications. In PHP, this can be achieved effectively using the date() function, which allows for combining hard-coded values with those extracted from timestamps.
For instance, to obtain the first and last dates of the current month, simply call date without providing a timestamp:
<code class="php">$first_day_this_month = date('m-01-Y'); $last_day_this_month = date('m-t-Y');</code>
Here, the symbols 'm' (month), '01' (first day), and 't' (last day) are used to specify the desired parts of the timestamp.
Similarly, to determine the last day of a specific month and year, like April 2010, you can pass the appropriate date string as the second argument to date() along with the timestamp:
<code class="php">$last_day_april_2010 = date('m-t-Y', strtotime('April 21, 2010'));</code>
The date() function offers a wide range of symbols for extracting various date and time components. For instance, to retrieve the first and last seconds of a month, you can use the following code:
<code class="php">$timestamp = strtotime('February 2012'); $first_second = date('m-01-Y 00:00:00', $timestamp); $last_second = date('m-t-Y 12:59:59', $timestamp);</code>
Refer to the PHP documentation for date() for a comprehensive list of supported symbols and additional information.
The above is the detailed content of How to Find the First and Last Days of a Month in PHP?. For more information, please follow other related articles on the PHP Chinese website!