goofyui goofyui - 1 year ago 111
SQL Question

How to cast the DateTime to Time

I am casting DateTime field to Time by using CAST Syntax.

select CAST([time] as time) as [CSTTime]

2015-03-19 00:00:00.000

Present Output : Time

I need only
and not Milliseconds or 0000's

How to filter or Cast it to exact HH:MM:SS Format.

Answer Source

Time is not stored with its display format in SQL Server.
therefore, from the user perspective, you can say that it has no format.
of course, that's not completely accurate since it does have a storage format, but as an average user you can't really use it.
This is true for all date and time data types:
(Date, DateTimeOffset, DateTime2, SmallDateTime, DateTime and Time).

If you need a format then you don't need to cast to time but to a char. Use Convert to get the char you need:

SELECT CONVERT(char(10), [time], 108) as CSTTime 

Here is some backgroud data if you're interested:

In this article published in 2000 the writer explains in depth how SQL Server treats dates and times. I doubt if anything significant changed between 2000 and 2015 in the way SQL Server stores date, time and datetime values internally.

Here are the relevant quotes, if you don't want to read all of it:

So how does SQL Server internally store the dates? It uses 8 bytes to store a datetime value—the first 4 for the date and the second 4 for the time. SQL Server can interpret both sets of 4 bytes as integers.
SQL Server stores the second integer for the time as the number of clock ticks after midnight. A second contains 300 ticks, so a tick equals 3.3 milliseconds (ms).

since time is actually stored as a 4 byte integer, it really doesn't have a format as an integral part of the data type.

You might also want to check out this article for a more detailed explanation with code samples.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download