I have a table in the MySQL database that is set up with DATETIME
. I need to SELECT
in this table only by DATE and excluding the time.
How d
if time column is on timestamp , you will get date value from that timestamp using this query
SELECT DATE(FROM_UNIXTIME(time)) from table
I solve this in my VB app with a simple tiny function (one line). Code taken out of a production app. The function looks like this:
Public Function MySQLDateTimeVar(inDate As Date, inTime As String) As String Return "'" & inDate.ToString(format:="yyyy'-'MM'-'dd") & " " & inTime & "'" End Function
Usage: Let's say I have DateTimePicker1 and DateTimePicker2 and the user must define a start date and an end date. No matter if the dates are the same. I need to query a DATETIME field using only the DATE. My query string is easily built like this:
Dim QueryString As String = "Select * From SOMETABLE Where SOMEDATETIMEFIELD BETWEEN " & MySQLDateTimeVar(DateTimePicker1.Value,"00:00:00") & " AND " & MySQLDateTimeVar(DateTimePicker2.Value,"23:59:59")
The function generates the correct MySQL DATETIME syntax for DATETIME fields in the query and the query returns all records on that DATE (or BETWEEN the DATES) correctly.
Yo can try this:
SELECT CURDATE();
If you check the following:
SELECT NOW(); SELECT DATE(NOW()); SELECT DATE_FORMAT(NOW(),'%Y-%m-%d');
You can see that it takes a long time.
Simply You can do
SELECT DATE(date_field) AS date_field FROM table_name