How to cast the DateTime to Time - sql

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.

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.

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

SQL Server 2008:
select cast(MyDate as time) [time] from yourtable
Earlier versions:
select convert(char(5), MyDate , 108) [time] from yourtable
Other Options:
SELECT CONVERT(VARCHAR(20), GETDATE(), 114)
The simplest way to get the time from datetime without millisecond stack is:
SELECT CONVERT(time(0),GETDATE())
Hour and Minute
SELECT substring(CONVERT(VARCHAR, GETDATE(), 108),0,6) AS Time

Related

SQL Server table's Column has date time value but in unrecognizable format

I am using SQL Server 2016 and have a table with one of the column datatype as BIGINT but its value is 1586862000000
This is not directly recognizable as DateTime value as datatype is also BIGINT, but the name of the column is PREV_EXEC_TIME which gives a hint that value is in DateTime but somewhat in encrypted form plus my guess is 15 stands for 3 pm as I had executed query at 15:00
So my concern is how can I convert this value to a standard DateTime format whenever I query (SELECT)on it
Is there some function like cast or convert to get expected output?
This looks like a Unix timestamp in milliseconds. If you are content with second-level precision, you can use:
select dateadd(second, 1586862000000 / 1000, '1970-01-01')
Unfortunately, SQL Server doesn't support dateadd_big(), but you can add the milliseconds separately if those are needed:
select dateadd(millisecond, 1586862000000 % 1000, dateadd(second, 1586862000000 / 1000, '1970-01-01'))

Concatenate Date and Time as DATETIME in SQL Server

I'm having a trouble in combining date and time to DATETIME. I have an existing table with data so I can't change it to Datetime2.
DECLARE #t1 TABLE(StartDate DATE, StartTime Time)
INSERT INTO #t1
VALUES('2018-02-28','08:00:00')
SELECT
CAST(CONCAT(StartDate, ' ', StartTime) AS DATETIME)
FROM #t1
The error shown is:
Conversion failed when converting date and/or time from character string.
Don't concat(). Just add but they both need to be datetime:
select cast(startdate as datetime) + cast(starttime as datetime)
The cast fails because the time component of the datetime data type has less precision than the time data type, as described on this page, which is a useful reference for the various date and time types offered by SQL Server. As you can also see on that page, SQL Server has a datetime2 data type that offers greater precision; if you had used that in your cast, I don't think you would have had a problem.
Gordon's solution is a good one in that it avoids the need to deal with conversions to and from strings in the first place. Just be aware that combining a date and time into a datetime may involve a loss of precision. See this question on the Stack Exchange DBA site for a solution with datetime2 that retains the precision of the original values.

How do I convert a value after using DATEADD with it

I have a little query that strips the date from the datetime field but when I try to convert it from GMT to CST it readds the date. Is there a better way to do this?
Location table:
arrival
4-6-2018 12:35:43
SELECT arrival
FROM(
SELECT CONVERT(VARCHAR(8), arrival))
FROM locations
)a
This query will give me this result:
12:35:43
SELECT (DATEADD(hour,-5,arrival))
FROM(
SELECT CONVERT(VARCHAR(8), arrival))
FROM locations
)a
4-6-2018 12:35:43
This query will give readd the date. How can I remove the date and then do the dateadd function without it readding the date
arrival seems to be a DateTime, which always carries a date part. You need a time instead, supported by SQL Server 2008+:
cast(DATEADD(hour,-5,arrival) as time)
To quote from DATEADD (Transact-SQL) - Return Types:
The return data type is the data type of the date argument, except for string literals. The return data type for a string literal is datetime. An error will be raised if the string literal seconds scale is more than three positions (.nnn) or contains the time zone offset part.
Emphasis my own.
As you are passing a string (varchar), then DATEADD is returning a datetime.
Like those in the comments have said, if you use the correct data type (time) this problem goes away:
SELECT DATEADD(HOUR, -5,CONVERT(time,Arrival))
FROM (VALUES('4-6-2018 12:35:43'),('4-6-2018 07:35:43'),('4-6-2018 03:35:43')) V(Arrival)
Probably this is what you are asking for:
SELECT Convert(Varchar(8), DATEADD(hour,-5,arrival), 108)
FROM locations;
Note: This is compatible with SQL server versions that doesn't have Time datatype too.

Time in datatime field

I have a field that stores the date and time but need to extract this so it only shows the time but shows the date as 01/01/1900.
I can extract the time using the below but need to include the data of 01/01/1900
convert(varchar(12), w.created, 114)
If you are using SQL Server, then you can do:
select cast('1900-01-01' as datetime) + cast(cast(w.created as time) as datetime)
This returns the value as a datetime.
SQL Server has a time data type. It is unclear why you would want to add in a fake date, but you can.

Storing the date Only in SQL Server 2005

How do I avoid storing the time portion of a datetime in SQL Server, i.e. if I have a value of 2011-01-01 00:00:00.000 I want to store only 2011-01-01?
I want to ensure that only the date portion is stored.
The DateTime data type ALWAYS stores the date AND time. So you are left with using CONVERT/CAST to obtain a particular format, or use the YEAR(), MONTH() or DAY() methods to isolate date details depending on your need.
SQL Server Date Formats.
The easiest solution is just to not expose the time portion to the user. However, if you really need to make sure only the date part is stored, you could force the time portion to midnight/midday/any constant time before storing the value.
The built-in DATETIME data type stores both the date and time data. If you specify only the date portion then the time will be 12:00:00 or something like that.
Funny story: I saw a database once where there was a date and a time field, both stored the date and the time, but each was used only for half of the data. Some people do silly things :)
If you cast a DateTime to an Int and back you will get a DateTime with 00:00 as the time part.
So you could save all your dates as integers in the database.
Either add a computed column:
dateonly AS CONVERT(DATETIME, CONVERT(CHAR(8), date_with_time, 112), 112)
or truncate your date right on insert:
INSERT
INTO mytable (dateonly)
VALUES CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112), 112)
, making a CHECK on your dateonly column to raise an error when someone tries to insert a non-truncated value:
CHECK (dateonly = CONVERT(DATETIME, CONVERT(CHAR(8), date_with_time, 112), 112))
Just represent the date as a yyyMMdd integer value.