Quantcast
Viewing all articles
Browse latest Browse all 10

Remove the time from a datetime in SQL

There are a few ways to remove the time from a datetime in SQL. This article descibes a couple of them.

This is the code: DATEADD(dd,0,DATEDIFF(dd,0,DateToRemoveTime))

I’ll explain how this works as it was quite confusing initially.

Part 1: DATEDIFF(dd,0,DateToRemoveTime)

What this is doing is finding the number of whole days (without time) from the beginning of time (0) to the date you want to remove the time (DateToRemoveTime).

Part 2: DATEADD(dd,0,Part1)

This is taking the number of whole days since time began which was calculated in Part 1 and adding this to the beginning of time (0).

As an example let’s say it’s 10.03 on the 14 Jan in Year 0. In SQL date format this would appear as something like 0000:01:14 10:03:00

Part 1 would see how many whole days have passed since the beginning of time, 0, and the 14 Jan in Year 0. This is 14 days. Part 2 would add these 14 days to the beginning of time – which would give the result 0000:01:14 00:00:00 – which is the date without the time.

Edit

In SQL 2008 there’s another way to do this using the DATE datatype. The syntax is very simple: CAST(DateToRemoveTime as DATE)

The next obvious question is which is the best method to use to remove the time portion from a date.

The post Remove the time from a datetime in SQL appeared first on Business Analytics.


Viewing all articles
Browse latest Browse all 10

Trending Articles