How to Get Month from Date in MySQL

how do I get month from date in mysql

You were close - got the comparison backwards (assuming startDate is a DATETIME or TIMESTAMP data type):

SELECT * 
FROM table
WHERE amount > 1000
AND MONTH(dateStart) = {$m}

Caveats:


  • Mind that you are using mysql_escape_string or you risk SQL injection attacks.
  • Function calls on columns means that an index, if one exists, can not be used

Alternatives:


Because using functions on columns can't use indexes, a better approach would be to use BETWEEN and the STR_TO_DATE functions:

WHERE startdate BETWEEN STR_TO_DATE([start_date], [format]) 
AND STR_TO_DATE([end_date], [format])

See the documentation for formatting syntax.

Reference:


  • MONTH
  • YEAR
  • BETWEEN
  • STR_TO_DATE

MySQL convert month number to month name

  • We can convert the given input number to MySQL date format (focusing on month only), using Str_To_Date() function.
  • Now, we simply need to use Monthname() function to extract the month name from the date.
  • This will work only when NO_ZERO_DATE mode is disabled.

Try:

SET sql_mode = ''; -- disable NO_ZERO_DATE mode
SELECT MONTHNAME(STR_TO_DATE(1, '%m'));

As @Felk suggested in comments, if we need to get shortened month name, we can use Date_Format() function instead:

SET sql_mode = ''; -- disable NO_ZERO_DATE mode
SELECT DATE_FORMAT(STR_TO_DATE(1, '%m'), '%b');

If you don't want to disable the NO_ZERO_DATE mode, then you can create any random date using the month and call Monthname():

SELECT MONTHNAME(CONCAT('2018-',3,'-1')); -- 3 is the input number

How to get difference between two dates in months using MySQL query?

The DATEDIFF function can give you the number of days between two dates. Which is more accurate, since... how do you define a month? (28, 29, 30, or 31 days?)

extract year and month from date field mysql

SELECT CONCAT(year(task_completion), '-' ,month(task_completion)) FROM task

MySQL DATETIME to MONTH only

I think you just want date_format():

SELECT sum(totalExcl) AS total, saleType, date_add,
date_format(date_add, '%M')
FROM ex.ps_ox_quo
WHERE WEEK(date_add) = WEEK(UTC_TIMESTAMP()) AND
saleType IN ('IEW')
GROUP BY date_add, saleType
ORDER BY date_add DESC;

Note: You should probably include the year in the date comparison.

Convert datetime to get month name in mysql

You could use concat

"select ..... 
...
where concat(MONTHNAME(S.date), ' ' , YEAR(S.date)) = '$date';"

Get records of current month

This query should work for you:

SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())

Extract month and year from mysql date format

You can try something like this in your query

SELECT b_date 
FROM summary
GROUP BY YEAR(b_date), MONTH(b_date)

Similar to this issue SQL group dates by month. My guess would be you are using MySQL, here are the docs for date manipulation



Related Topics



Leave a reply



Submit