How do i show just the time with AM or PM from a field that is a datetime format? - sql

I have a column of data in SQL that is currently in the datetime format. It can be changed if needed. I need to show just the time of day, to the 10th of a second, with either AM or PM attached also. I do not want the date to be shown in this instance.
So instead of '1900-01-01 11:45:59.800' as an example, i need '11:45:59.8 AM'.
Also, this is not a current "getdate" time. It is from a field of data i have called 'Time'
I see all sorts of convert formats on the web, but none will pull this up for me.
Thank you!!!!

As in my comment, I'd advise you to not do this.
SQL Server is a place for data, and converting the data for display purposes is often a blurring of the lines that can come back to haunt you. (One example; what if you need that time as a Time somewhere else in the future. Are you going to convert it back from a string again?)
If it is Necessary, then you have to do some of the formatting yourself.
SELECT
RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109), 14)
Or, more messy...
SELECT
DATEPART(HOUR, GETDATE()) + ':' +
DATEPART(MINUTE, GETDATE()) + ':' +
DATEPART(SECOND, GETDATE()) + '.' +
DATEPART(MILLISECOND, GETDATE()) +
CASE WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 'AM' ELSE 'PM' END
Did I say? You're better doing it on the client side ;)

Rename your table field, Time is a reserved word and it will be a pain to maintain. Make sure you are using the new datetime2 data type if you want millisecond accuracy.
To format the time part use:
SELECT CONVERT(TIME, [Time]) FROM [Your Table]
If you only want a three digits after the period you can use:
SELECT CONVERT(TIME(3), [Time]) FROM [Your Table]

I think this will work if you want to get in HH:MM format
SELECT
RIGHT(CONVERT(VARCHAR(26), GETDATE(), 117), 14)
You can also refer to this page for more formats
http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36271.1570/html/blocks/X41864.htm

Related

SQL Round Seconds on Column to 00 seconds [duplicate]

I'm having a bit of trouble with truncating data. I'm using SQL's GETDATE() function to get the current date and time and enter them into a database. However, I only want to save the date and time up until the minute. In other words, I want dd/mm/yyyy hh:mm:00.000 or dd/mm/yyyy hh:mm to be saved when I input new data. How can I go about doing this?
I should note I'm using MS-SQL.
There are a number of ways to go about doing this.
For example, you could convert the generated datetime from GetDate() to a smalldatetime first, à la:
CAST(GetDate() AS smalldatetime)
To be clear, this will round the generated seconds up (or down) to the nearest minute depending up the value of the current second.
EDIT:
Alternatively, you can have SQL Server truncate a datetime for you for a "cleaner" (READ: no rounding, since the value is pre-truncated) conversion to smalldatetime:
CAST(DateAdd(minute, DateDiff(minute, 0, GetDate()), 0) AS smalldatetime)
For truncation:
SELECT SMALLDATETIMEFROMPARTS(
datepart(year ,dt)
,datepart(month ,dt)
,datepart(day ,dt)
,datepart(hour ,dt)
,datepart(minute,dt)
)
FROM (SELECT GETDATE()) t(dt)
One way is to convert it to smalldatetime for the assignment (and back as needed).
smalldatetime always has seconds and beyond set to 00.
SELECT CONVERT(smalldatetime, GETDATE())
As this may round up or down, another way to safely truncate the seconds would be this:
SELECT CONVERT(datetime, CONVERT(nchar(16), GETDATE(), 120), 120)
The conversion code 120 returns the format yyyy-mm-dd hh:mi:ss.
Combine DATEADD and SMALLDATETIME to truncate
CAST(DATEADD(S, -30, dt) AS SMALLDATETIME)
The other option is not sure why you cannot consider the front-end instead of the back-end so don't change the SQL and thus format in the front-end as dd/MM/yyyy HH:mm or whatever format you need if that is doable or appropriate in the context of what you are trying to achieve. For example in an SSRS report you could format the field in question in the report designer or use the Format function. If it is a webpage or Excel I am sure you could also do something similar.

Convert date format doesn't take effect on self made date string in SQL Server

I have a rather strange issue here. I have a date string, which I've created partly by myself to incorporate a variable. The problem is, that I'm setting another language settings. In this case, I have to also convert the string to fit the language settings format. I'm using this code:
cast(convert(varchar, cast(cast(getdate() as date) as varchar) + ' ' + RIGHT('0' + CAST(#HR as varchar), 2) + ':00:00.000', 120) as datetime)
I get the error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.", which is normal if you assign wrong date format before casting.
The problem is, that when I try to convert the personally created date string, it doesn't change its format no matter what format code I set it in. That doesn't change even when I hardcode a number instead of my variable:
convert(varchar, cast(cast(getdate() as date) as varchar) + ' 0' + CAST(2 as varchar) + ':00:00.000', 101)
results in 2016-09-14 02:00:00.000
For example,
convert(varchar, dateadd(Hour, 2, getdate()), 101) as datetime
Results in 09/14/2016.
Even though I have a different language setting, isn't SQL server supposed to always recognize the date format in the standard format?
Please give me an advice so I can overcome this issue.
Thanks in advance!
PS: I managed to solve my issue by inserting converted datetime column in a variable before setting bulgarian language. I'm still very interested to know what causes the problem though.
Ok I may have a soution for the question: Why is the format differently handled in SQL-SERVER when converting.
CONVERT(data_type(length),expression,style)
The STYLEvalue only applies for date/time.
So it's because of the datatype that the output is different.
See following example:
SELECT convert(varchar, dateadd(Hour, 2, getdate()), 101) as datetime
You get the result:
09/14/2016
Here your are converting a datetime datatype into a varchar and the STYLE-value with 101 applies for CONVERT and the output is converted in that format.
Example 2 is the same but the inner most part is casted into a varchar before converting it:
SELECT convert(varchar, CAST(dateadd(Hour, 2, getdate()) AS varchar), 101) as datetime
The result you get is:
Sep 14 2016 4:09PM
So because we are trying to convert a varchar into a varchar the STYLE-value doesn't apply for the conversion.
That is also why the first query is handled diffrent then the other:
SELECT convert(varchar, cast(cast(getdate() as date) as varchar) + ' 0' + CAST(2 as varchar) + ':00:00.000', 101)
Here you cast into varchar cast(cast(getdate() as date) as varchar) before converting. So the STYLE-value is not applying because it's not from datatype date/time.
I hope it made it a bit clear. Let me know if this helped.
When you use convert to format the datetime, you can pass a style number to it.
Looky here or here for those numbers.
The query below converts custom created datetimes to the 126 (ISO8601) format.
declare #d int = 2;
SELECT
CONVERT(varchar,
CONVERT(datetime,
CONCAT(FORMAT(GETDATE(),'yyyy-MM-dd'),' ',#d,':0')
)
,126) AS MyDateStamp1,
CONVERT(varchar,
CONVERT(datetime,
CONVERT(varchar,GETDATE(),102)+' '+convert(varchar,#d)+':0'
)
,126) AS MyDateStamp2;
The FORMAT & CONCAT functions can be used in SQL Server 2012 and beyond.
But if you have an earlier version then CONVERT should work instead.
Additional tip:
If you're using the CONVERT solution above, note that
"convert(varchar, CAST(dateadd(Hour, 2, getdate()) AS varchar), 101)" calls for you to set datatype to varchar.
I just came across code
"Convert(date,ML.StartDate,101)"
and since style 101 is mm/dd/yyyy, and the output was yyyy-mm-dd, I knew something was wrong. By changing the code to
"Convert(varchar,ML.StartDate,101)"
the proper date style was displayed in the result set.

Convert time in SQL to 12 hour format WITH seconds on

I have a script that I am using to populate a time dimension table and I would like to have a column for the time in 12 hour format.
I know this can be done by doing something along the lines of
SELECT CONVERT(varchar(15),[FullTime],100)
Where [FullTime] is a column containing a TIME field in HH:MM:SS format.
But this gives the following result 2:30pm and I would like 2:30:47PM, note the inclusion of seconds.
I know I could build this up using substrings etc. but I wondered if there was a prettier way of doing it.
Thanks
SELECT GETDATE() 'Today',
CONVERT(VARCHAR(8), [FullTime], 108) 'hh:mi:ss'
Taken from here
This will give you a column 'today' followed by the time value you seek 'hh:mi:ss'
If having also milliseconds is not a problem for you, you can use
SELECT CONVERT(VARCHAR, [FullTime], 109)
Declare #tstTime datetime
set #tstTime = GetDate()
Select
#tstTime
,CONCAT(SUBSTRING(CONVERT(varchar(26), #tstTime, 109),1,20),RIGHT(CONVERT(varchar(26), #tstTime, 109),2))

Truncate seconds and milliseconds in SQL

I'm having a bit of trouble with truncating data. I'm using SQL's GETDATE() function to get the current date and time and enter them into a database. However, I only want to save the date and time up until the minute. In other words, I want dd/mm/yyyy hh:mm:00.000 or dd/mm/yyyy hh:mm to be saved when I input new data. How can I go about doing this?
I should note I'm using MS-SQL.
There are a number of ways to go about doing this.
For example, you could convert the generated datetime from GetDate() to a smalldatetime first, à la:
CAST(GetDate() AS smalldatetime)
To be clear, this will round the generated seconds up (or down) to the nearest minute depending up the value of the current second.
EDIT:
Alternatively, you can have SQL Server truncate a datetime for you for a "cleaner" (READ: no rounding, since the value is pre-truncated) conversion to smalldatetime:
CAST(DateAdd(minute, DateDiff(minute, 0, GetDate()), 0) AS smalldatetime)
For truncation:
SELECT SMALLDATETIMEFROMPARTS(
datepart(year ,dt)
,datepart(month ,dt)
,datepart(day ,dt)
,datepart(hour ,dt)
,datepart(minute,dt)
)
FROM (SELECT GETDATE()) t(dt)
One way is to convert it to smalldatetime for the assignment (and back as needed).
smalldatetime always has seconds and beyond set to 00.
SELECT CONVERT(smalldatetime, GETDATE())
As this may round up or down, another way to safely truncate the seconds would be this:
SELECT CONVERT(datetime, CONVERT(nchar(16), GETDATE(), 120), 120)
The conversion code 120 returns the format yyyy-mm-dd hh:mi:ss.
Combine DATEADD and SMALLDATETIME to truncate
CAST(DATEADD(S, -30, dt) AS SMALLDATETIME)
The other option is not sure why you cannot consider the front-end instead of the back-end so don't change the SQL and thus format in the front-end as dd/MM/yyyy HH:mm or whatever format you need if that is doable or appropriate in the context of what you are trying to achieve. For example in an SSRS report you could format the field in question in the report designer or use the Format function. If it is a webpage or Excel I am sure you could also do something similar.

sql cast hour out of datetime without dropping leading zero on single digit hours

CAST(DATEPART(hh, timestamp) AS varchar(2)) + ':00' AS Hour
This will get me the hour out of a timestamp field but in the case of the hours 0-9 it does not pad a leading zero and therefore when I sort by hour descending it does not sort correctly.
Not sure what is wrong here. I specify a 2 char varchar to allow extra room for the leading zero. Hopefully there is a way to fix this without passing my field through a function that will pad the leading zero for me.
SELECT RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(HOUR, GETDATE())), 2) + ':00';
Don't want to pad with 0s? OK, you can do it a similarly ugly way without the padding mess:
SELECT LEFT(CONVERT(TIME(0), GETDATE()), 2) + ':00';
Obviously replace GETDATE() with your column name. Which I hope isn't really timestamp because this is a reserved word - for a data type that has nothing to do with date or time, sadly.
If you don't like either of those solutions, then just select the data from SQL Server and let your client application handle formatting/presentation details. Surely this is easy to do with C#'s format() function, for example.
Assuming timestamp is a column in your table
select convert(char(3), timestamp, 108) + '00' AS Hour
from yourtable
Alternative
select left(cast(dateadd(hh, datediff(hh, 0, timestamp), 0) as time), 5)
from yourtable
Edit:
After testing a bit i came to the conclusion that this is the fastest way (almost the performance and syntax as Aaron's solution)
SELECT RIGHT(100 + DATEPART(HOUR, timestamp) , 2) + ':00'
from yourtable
You can use the TIME type which is 24 hours by default;
cast(cast(timestamp as time) AS varchar(2)) + ':00' AS Hour