How to Get the Year and the Month From a Date in MySQL

Last updated 2 years ago

...

To extract the month and year from a specified date stored in a MySQL database is your objective.

Example:
The information in our database is stored in a table called "impression" that comprises of two columns, namely "id" and "date."

iddate
22023-04-28
42023-06-26
52022-04-26
62021-04-26

We shall retrieve the year and month values from the given date.

 

Methods 1.

SELECT EXTRACT(YEAR FROM date) AS year, EXTRACT(MONTH FROM date) AS month FROM impression;

Output:

yearmonth
20234
20236
20224
20214

To retrieve the year and month columns, employ the EXTRACT(part FROM date) function. In this particular method, YEAR and MONTH subsitute the part parameter to obtain and segregate the year and month into individual columns.

 

Methods 2.

SELECT EXTRACT(YEAR_MONTH FROM date) AS year_and_month FROM impression;

Output:

year_and_month
202304
202104
202304
202304

The previous method and this solution operate similarly, with the exception that YEAR_MONTH retrieves both the year and month together in a solitary column rather than as distinct entities. Please note that the year and month values are not isolated from each other.

 

Methods 3.

SELECT YEAR(date) AS year, MONTH(date) AS month FROM impression;

Output:

yearmonth
20234
20214
20234
20234

In this instance, we have utilized the YEAR() and MONTH() functions to form a pair of columns. The YEAR() function furnishes the year, while the MONTH() function produces the month represented as a numerical value.

 

Methods 4.

SELECT YEAR(date) AS year, MONTHNAME(date) AS month FROM impression;

Output:

yearmonth
2023April
2021April
2023April

Use the MONTHNAME() function to obtain the name of the month. The output exhibits the name of the month rather than its corresponding number.

 

Methods 5.

SELECT DATE_FORMAT(date, '%Y-%m') AS year_and_month FROM impression;


Output:

year_and_month
2023-04
2021-04
2023-04
2023-04

 


How to Extract a Substrin...

How to Extract a Substring From a String in MySQL

Read It

An Introduction To CSS Pr...

CSS or Cascading Style Sheets have become a really popular programming language in recent times and...

Read It



----Advertisement----