Removing time from a datetime field in SQL

I’ve got a small project at work that required me to use the date, but not the time in a datetime field for retrieval of certain rows from a table in SQL Server 2000. A bit of Googling revealed a document titled “Remove seconds from datetime SQL“. The title isn’t quite right, as the author’s query removes hours and minutes too, but the result turned out to be just what I wanted.

The query: SELECT Cast(Convert(varchar, GetDate(),105) as datetime)

I ended up using code 101 instead of 105 to get my query working, but that was it.

Comments

  1. James says:

    Another option is to use:

    DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)

    This just adds back the number of days since the minimum date, to the minimum date which effectively eliminates the time portion of the datetime.

  2. Shirley says:

    Can anyone give an example of the linq to sql equivalent of these SQL expressions? In other words: What is the best way to remove the time from a datatime field in linq to sql??

    • Clay Anderson says:

      If you’re using LINQ to SQL, you can use the .Date property of a DateTime object to get the date portion.

      db.Records.Where(row => row.EventDate.Date == dateFilter)

  3. Pete says:

    SQL 2008 does have a new data type called date only,

    it does require you to remove the time part thogh before inserting innto it.

    ie if using .net you would need to use .toshortdate.tostring

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.