Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast the DateTime to Time

Tags:

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

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

DateTime 2015-03-19 00:00:00.000

Present Output : Time 03:05:36.0000000

I need only HH:MM:SS and not Milliseconds or 0000's

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

like image 436
goofyui Avatar asked May 04 '15 14:05

goofyui


People also ask

How do you convert date to time?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do I get time in HH MM format in SQL?

By using format code as 106 we can get datetime in “DD MMM YYYY” format. By using format code as 107 we can get datetime in “MMM DD, YYYY” format. By using format code as 108 we can get datetime in “HH:mm: ss” format. By using format code as 109 we can get datetime in “MMM DD YYYY hh:mm:ss:fff(AM/PM)” format.


2 Answers

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 background 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.

like image 145
Zohar Peled Avatar answered Sep 28 '22 18:09

Zohar Peled


You can achieve it with CAST just simple use TIME(0) datatype in following:

SELECT CAST('2015-03-19 01:05:06.289' AS TIME(0))

OUTPUT:

01:05:06

like image 34
Stanislovas Kalašnikovas Avatar answered Sep 28 '22 18:09

Stanislovas Kalašnikovas