Home > Database > Mysql Tutorial > How to Find the First Day of the Month for a Given Date in MySQL?

How to Find the First Day of the Month for a Given Date in MySQL?

Susan Sarandon
Release: 2024-11-16 00:44:03
Original
508 people have browsed it

How to Find the First Day of the Month for a Given Date in MySQL?

Query to Retrieve the First Day of Each Month corresponding to a Given Date

To obtain the first day of each month corresponding to a specified date, we can utilize MySQL's built-in date manipulation functions.

Query Formulation:

To determine the first day of the month corresponding to a given date, we can apply the following query:

SELECT CAST(DATE_FORMAT(DATE_SUB(?, INTERVAL DAYOFMONTH(?) - 1 DAY), '%Y-%m-01') AS DATE);
Copy after login

where:

  • ? represents the date value specified by the user (e.g., '2010-06-15')

Query Explanation:

  • DATE_SUB(?, INTERVAL DAYOFMONTH(?) - 1 DAY): This expression calculates the date one day before the first day of the month corresponding to the given date.
  • DAYOFMONTH(?) - 1: This expression subtracts one from the day of the month to obtain the last day of the previous month.
  • %Y-%m-01 is a string literal specifying the desired date format, which includes the year, month, and day (set to the first day of the month).

To illustrate the query's functionality:

  • Input: '2010-06-15'
  • Output: '2010-06-01' (desired first day of the month)

The above is the detailed content of How to Find the First Day of the Month for a Given Date in MySQL?. 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