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
Select * from table_name where date(datetime)
you can use date_format
select DATE_FORMAT(date,'%y-%m-%d') from tablename
for time zone
sql2 = "SELECT DATE_FORMAT(CONVERT_TZ(CURDATE(),'US/Central','Asia/Karachi'),'%Y-%m-%d');"
You can use select DATE(time) from appointment_details
for date only
or
You can use select TIME(time) from appointment_details
for time only
Try to use
for today:
SELECT * FROM `tbl_name` where DATE(column_name) = CURDATE()
for selected date:
SELECT * FROM `tbl_name` where DATE(column_name) = DATE('2016-01-14')
SELECT DATE_FORMAT(NOW() - INTERVAL FLOOR(RAND() * 14) DAY,'%Y-%m-%d');
This one can be used to get date in 'yyyy-mm-dd' format.
I tried doing a SELECT DATE(ColumnName)
, however this does not work for TIMESTAMP
columns† because they are stored in UTC and the UTC date is used instead of converting to the local date. I needed to select rows that were on a specific date in my time zone, so combining my answer to this other question with Balaswamy Vaddeman's answer to this question, this is what I did:
DATETIME
Just do SELECT DATE(ColumnName)
TIMESTAMP
Load the time zone data into MySQL if you haven't done so already. For Windows servers see the previous link. For Linux, FreeBSD, Solaris, and OS X servers you would do:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
Then format your query like this:
SELECT DATE(CONVERT_TZ(`ColumnName`, 'UTC', 'America/New_York'))
You can also put this in the WHERE
part of the query like this (but note that indexes on that column will not work):
SELECT * FROM tableName
WHERE DATE(CONVERT_TZ(`ColumnName`, 'UTC', 'America/New_York')) >= '2015-02-04'
(Obviously substitute America/New_York
for your local time zone.)
† The only exception to this is if your local time zone is GMT and you don't do daylight savings because your local time is the same as UTC.