How to Find the First and Last Dates of a Month in PHP?

Linda Hamilton
Release: 2024-11-02 02:31:02
Original
169 people have browsed it

How to Find the First and Last Dates of a Month in PHP?

Finding the First and Last Dates in a Month Using PHP

PHP offers a powerful function called date that allows you to retrieve and format various information from timestamps. This includes finding the first and last dates in a given month.

Finding Dates for the Current Month

To find the first and last dates of the current month, you can simply specify the "m-01-Y" and "m-t-Y" format strings, respectively. These represent the first day of the month (with a hard-coded '01') and the last day of the month (indicated by 't'). For example:

<code class="php">$first_day_this_month = date('m-01-Y'); // hard-coded '01' for first day
$last_day_this_month  = date('m-t-Y');</code>
Copy after login

Finding Dates for Specific Months

To find the first and last dates for a specific month, you can specify a timestamp. This can be a string in a recognized date format or a UNIX timestamp. For example, to find the last day of April 2010:

<code class="php">$last_day_april_2010 = date('m-t-Y', strtotime('April 21, 2010'));</code>
Copy after login

Understanding the Format Symbols

date() interprets specific symbols within the format string and replaces them with values from the timestamp. The symbols used for extracting month and day values are:

  • Y: 4-digit year
  • m: Numeric month with leading zero
  • t: Number of days in the month

Additional Examples

  • Find the first and last second of a month:
<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>
Copy after login

For more detailed information on the date() function and available format symbols, refer to the official PHP manual: http://php.net/manual/en/function.date.php.

The above is the detailed content of How to Find the First and Last Dates of a Month in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!