You can use the MONTH()
function in MySQL to return the month from a date.
In this context, the month is a value between 1 and 12 (or 0 for dates with a zero month part).
For example, if you provide a date of 2018-10-07, the MONTH()
function will return 10.
Syntax
The syntax goes like this:
MONTH(date)
Where date
is the date value that you want the month returned from.
Example
Here’s an example to demonstrate.
SELECT MONTH('2020-12-18') AS 'Result';
Result:
+--------+ | Result | +--------+ | 12 | +--------+
If the month part has a leading zero, the leading zero is omitted from the result. Example:
SELECT MONTH('2020-07-18') AS 'Result';
Result:
+--------+ | Result | +--------+ | 7 | +--------+
A Database Example
In this example, I extract the month part from a column when running a query against a database.
USE sakila; SELECT payment_date AS 'Date/Time', MONTH(payment_date) AS 'Month' FROM payment WHERE payment_id = 1;
Result:
+---------------------+-------+ | Date/Time | Month | +---------------------+-------+ | 2005-05-25 11:30:37 | 5 | +---------------------+-------+
Current Date/Time
Here’s an example of extracting the month part from the current date and time (which is returned using the NOW()
function).
SELECT NOW(), MONTH(NOW());
Result:
+---------------------+--------------+ | NOW() | MONTH(NOW()) | +---------------------+--------------+ | 2018-06-29 14:44:38 | 6 | +---------------------+--------------+
Another way to do this is to use the CURDATE()
function, which returns only the date (but not the time).
SELECT CURDATE(), MONTH(CURDATE());
Result:
+------------+------------------+ | CURDATE() | MONTH(CURDATE()) | +------------+------------------+ | 2018-06-29 | 6 | +------------+------------------+