Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting date range MySQL with date_format

I've got an issue selecting a date range with MySQL.

SELECT MvtDate,date_format(MvtDate,'%d-%m-%Y')
  FROM (`immmvt`)
 WHERE date_format(MvtDate,'%d-%m-%Y') BETWEEN '01-01-2010' AND '02-01-2010'

mvtDate type is date like 2010-01-01 00:00:00.

When I run the query, the result works for the days and the months but it also show me other result from other years.

Like 01-01-2011 etc.

like image 782
user1749399 Avatar asked Oct 16 '12 08:10

user1749399


People also ask

How do I select a date range in MySQL?

How to Select rows from a range of dates with MySQL query command. If you need to select rows from a MySQL database' table in a date range, you need to use a command like this: SELECT * FROM table WHERE date_column >= '2014-01-01' AND date_column <= '2015-01-01';

How can get date in dd mm yyyy format in MySQL?

The following is the output. The following is the query to format the date to YYYY-MM-DD. mysql> select str_to_date(LoginDate,'%d. %m.

How can I get data between two dates in MySQL?

Use the DATEDIFF() function to retrieve the number of days between two dates in a MySQL database.

How do I get Saturday and Sunday between two dates in MySQL?

MySQL WEEKDAY() Function The WEEKDAY() function returns the weekday number for a given date. Note: 0 = Monday, 1 = Tuesday, 2 = Wednesday, 3 = Thursday, 4 = Friday, 5 = Saturday, 6 = Sunday.


2 Answers

You should use STR_TO_DATE since you want to convert string back to date

SELECT MvtDate, date_format(MvtDate,'%d-%m-%Y')
FROM  `immmvt`
WHERE MvtDate BETWEEN STR_TO_DATE('01-01-2010','%d-%m-%Y') AND 
                      STR_TO_DATE('02-01-2010','%d-%m-%Y')
FYI: DATE_FORMAT() converts date to formatted string representation.
     STR_TO_DATE() converts formatted string back to date
like image 180
John Woo Avatar answered Oct 03 '22 02:10

John Woo


SELECT MvtDate,date_format(MvtDate,'%d-%m-%Y')
  FROM (`immmvt`)
 WHERE date_format(MvtDate,'%d-%m-%Y') IN ('01-01-2010', '02-01-2010')
like image 30
Salil Avatar answered Oct 03 '22 00:10

Salil