Time in datatime field - sql

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.

Related

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.

How to convert a datetime column to another column using just the date part plus a hardcoded time in SQL

How can I combine the datetime column (but just the date part, not the time part of it) with a hardcoded time stamp like 06:00:00 AM? I want to convert a current datetime field using the date portion of it + the 6AM time stamp to then use in a case scenario.
For example:
case
when event_datetime > datetimefield+06:00:00 AM
then 'late'
Convert both to DATE while in the CASE. Converting them to DATE will drop the time information. If you are using these fields again, I would recommend you convert them both to DATE, store them variables or temp table then utilize them.
CASE WHEN CONVERT(DATE, EVENTDATETIME) > CONVERT(DATE,DateTimefield)
THEN 'Late'
I ended up using DATEADD:
CASE WHEN event_datetime > DATEADD(HOUR,6,datetime field) THEN 'event_late'
CASE WHEN event_datetime <= DATEADD(HOUR,6,datetime field) THEN 'event_ontime'
ELSE 'event_unkwn'
END AS event_outcome
This helped me convert the datetime field to the date+06:00 AM (As date format) for the comparison with the event_datetime to work.

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]
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

SQL - comparing date parameter to datetime

In a SQL Server table, I have a field named Timestamp, which is a 'datetime' field. On a screen I have created, a user will pass in a date (no time), and I need to return all the records for that date.
Just doing Timestamp = #Date doesn't seem to work unless the time in the field is 00:00:00. What is the most efficient way of doing this?
Since you're on SQL Server 2008, you can use the DATE datatype.
Do a comparison between
CAST(Timestamp AS DATE) = #Date
That should work and look just at the date - no time portion.
In general you should think about the data from a specific date as data that falls in a range, not at a single point in time. So ideally your query should use a range, such as:
WHERE [Timestamp] >= #Date
AND [Timestamp] < DATEADD(DAY, 1, #Date)
In this case, luckily, the optimizer is smart and will still use an index if you use CONVERT(DATE, [timestamp]) against the column. However in a lot of cases you need to be careful because this will often make your clause non-sargable.
PS Timestamp is a horrible column name. It's a data type in SQL Server which has nothing to do with date or time.
A common technique for truncating the time part off a datetime value is to use the DATEDIFF and DATEADD functions. In your example it would be used like this to truncate the time part of the Timestamp field.
WHERE #DateEntered = DATEADD(DAY,0, DATEDIFF(DAY, 0, Timestamp))
Bascially it's taking the datetime value and finding the name of days since "the date represented by 0" (for lack of a better description) and then adding that number of days back. This effectively truncates time part.

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.