How to select only date from a DATETIME field in MySQL?

前端 未结 16 1932
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 04:37

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

相关标签:
16条回答
  • 2020-11-28 04:54
    Select * from table_name where date(datetime)
    
    0 讨论(0)
  • 2020-11-28 04:56

    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');"
    
    0 讨论(0)
  • 2020-11-28 04:56

    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

    0 讨论(0)
  • 2020-11-28 04:56

    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')
    
    0 讨论(0)
  • 2020-11-28 04:58
    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.

    0 讨论(0)
  • 2020-11-28 05:02

    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:

    If you are storing dates as DATETIME

    Just do SELECT DATE(ColumnName)

    If you are storing dates as 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.

    0 讨论(0)
提交回复
热议问题