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

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

Related

SQL Creating a table for song duration

I am trying to create a table in SQL which is about Music, it should contain songDuration. Which means I gotta hold minutes:seconds information in the table. But i have no idea what to use for the type. I am using SQL server.
Edit: I want to use the database for an ASP.NET Core web application. I was using a ready-to-use SQL database like northwnd. Now, I am trying to create one. So, I will not see the timing with SELECT function in SQL query. So, I need to use something that makes it mm:ss otomaticly. Is there is a type that I can decleare like that?
create table musics(
songDuration type,
...)
Why just don't you use int?
So you could calculate duration in the way you like.
E.g. minutes,hours, etc.
There's a datatype time which would be the logical choice, that stores it in format HH:mm:ss with an optional amount of fractional seconds determined by the size you declare the field (e.g. time(3) holds it to three decimal places)
If your source data is already in this notation it makes it getting it in the table easy and simple sorting/filtering operates as you expect. The downside to doing this is if you want to do certain operations such as SUM or AVG (because as a_horse_with_no_name pointed out in their comment) time technically represents a point in time not a duration and you'd have to do some workaround like so:
SELECT totalduration = SUM(DATEDIFF(SECOND, '0:00:00', duration))
FROM dbo.table
Alternatively you could store the number of (say) seconds in the duration using an int, but if you don't already have the information in that format you'd have to do some (light) conversion when inserting the data, and then back if you want to display in mm:ss
e.g:
SELECT CONVERT(varchar, DATEADD(SECOND, durationinseconds, 0), 8) FROM dbo.table
which would convert it back to hh:mm:ss format.
I do this by using an int column, and store the seconds there.
In your client you can calculate from the seconds howmany days, hours, minutes and seconds it is and display it like you want.
To display it in sql you can use this for example
declare #seconds int = 350
select right('00' + convert(varchar, datepart(hour, dateadd(s, #seconds, 0)) + ((#seconds / 86400) * 24)), 2)
+ ':' + right('00' + convert(varchar, datepart(minute, dateadd(s, #seconds, 0))), 2)
+ ':' + right('00' + convert(varchar, datepart(second, dateadd(s, #seconds, 0))), 2)
this will display
00:05:50
which is 0 hours, 5 minutes and 50 seconds
IF the value of seconds is larger than a day, this will be no problem. The number of hours will simply be greater
a value of 350000 will display 97:13:20

SQL Server Converting Decimal into Time hh:mm, I need the total hours

I need to be able to get the total hours and minutes if it is over 24 hours from a decimal column in SQL Server.
This is the code I am using:
CAST(CAST(DATEADD(SECOND, 1654.86 * 60, 0) AS Time(0)) AS VARCHAR(5))
Since it's over 24 hours the output is "03:34" I would like for it to be "27:34" or if possible to tell me it will take 3 working days and "03:34" (not sure how that would work).
Thank you in advance! Paul
As explained in the comments, the time data type is not designed to represent any sort of interval or timespan, it is only designed to represent clock time. As such, it is not capable of displaying 27 hours. Instead you need to build this string yourself with methods other than simple CAST as type:
DECLARE #d table(decimal_column decimal(15,2));
INSERT #d(decimal_column) VALUES(1654.86);
SELECT d.decimal_column,
nice_time = CONVERT(varchar(11), FLOOR(h)) + ':'
+ RIGHT('0' + CONVERT(varchar(11), FLOOR(m)), 2)
FROM #d AS d
CROSS APPLY
(
VALUES(d.decimal_column/60, d.decimal_column%60)
) AS extracted(h,m);
Results:
decimal_column
nice_time
1654.86
27:34
Example db<>fiddle
You may have edge cases where you want actual rounding logic instead of FLOOR() - but if you have those cases, include them in your question so we know the desired output.
select CONVERT(VARCHAR, CONVERT(INT, 1654.86/60)) + ':'
+ CONVERT(VARCHAR, CONVERT(INT, 1654.86-(CONVERT(INT, 1654.86/60)*60)))
You can create a function for this query, it is very performance. Because we will not use the same operations in multi sections.

Need part of a date

I am using SQL Server 2008R2.
I am trying to get part of a date in an output, and my column is in datetime datatype.
Eg,
If Current date and time is 2016-06-28 17:34:12.060, then I need output as 17:00 only the Hour with :00 mins.
I have tried this until now,
Select DateName(HH,SUBSTRING('2016-06-28 17:34:12.060',12,5)) +':00'
which gives me right output.But when I pass Column Name which is of datetime datatype, then it gives error,
Select DateName(HH,SUBSTRING(TimeInHour,12,5)) +':00'
gives error,
Argument data type time is invalid for argument 1 of substring function.
I know I am using SUBSTRING() at wrong place, But I really don't know how to achieve that output.
A help will be much appreciable.I need output as HH:00, Hour will be anything but 00 mins.
Why would you use substring() at all? The second argument to datename() should be a date/time data type. So, just do:
Select DateName(hour, '2016-06-28 17:34:12.060') + ':00'
Try this:
Select CAST(DATEPART(hour,'2016-06-28 17:34:12.060') AS VARCHAR(2)) +':00'
Below is the code that might be helpful
SELECT CONVERT(VARCHAR(50),DATEPART(YY,'2016-06-28 17:34:12.060')) -- Year
SELECT CONVERT(VARCHAR(50),DATEPART(mm,'2016-06-28 17:34:12.060')) -- Month
SELECT CONVERT(VARCHAR(50),DATEPART(d,'2016-06-28 17:34:12.060')) -- Day
SELECT CONVERT(VARCHAR(50),DATEPART(HH,'2016-06-28 17:34:12.060'))+':00' -- Hour
SELECT CONVERT(VARCHAR(50),DATEPART(mi,'2016-06-28 17:34:12.060'))+':00' -- Minutes
SELECT CONVERT(VARCHAR(50),DATEPART(ss,'2016-06-28 17:34:12.060')) -- Seconds
SELECT CONVERT(VARCHAR(50),DATEPART(ms,'2016-06-28 17:34:12.060')) -- Millisecond
You need to cast your DATETIME type column first, Use CAST function
Select DateName(HH,SUBSTRING(CAST(ColumnName AS VARCHAR(30)),12,5)) +':00'
Or alternative to do is Use LEFT and CONVERT
SELECT LEFT(CONVERT(VARCHAR, ColumnName ,108),2)+':00'
select convert(varchar, datepart(hour, getdate())) + ':' + convert(varchar, datepart(second, getdate()))

DATENAME and DATEPART in SQL

I'm trying to get my EntryDate column in this format 'YYYY_m' for example '2013_04'.
This code has been unsuccessful
DATENAME (YYYY, EntryDate) + '_' + DATEPART (M, EntryDate)
Attempts using DATEFORMAT have also been unsuccessful, stating there was syntax error at ',' after the M. What code would work instead?
Thank you.
How about date_format()?
select date_format(EntryDate, '%&Y_%m')
This is the MySQL way. Your code looks like an attempt to do this in SQL Server.
EDIT:
The following should work in SQL Server:
select DATENAME(year, EntryDate) + '_' + RIGHT('00' + DATEPART(month, EntryDate), 2)
Personally, I might use convert():
select replace(convert(varchar(7), EntryDate, 121), '-', '_')
select DATENAME (YYYY, EntryDate)
+ '_'
+ right('0' + convert(varchar(2),datepart (MM, EntryDate)), 2)
You have to convert the result of DATEPART() to a character string in order for the + to perform an append.
FYI - in the future "unsuccessful" doesn't mean anything. Next time post the actual error you are receiving.
For example:
SELECT concat(EXTRACT(YEAR FROM '2015/1/1'), '_',
LPAD(extract(month from '2014/1/1'),2,'0')) AS OrderYear
This uses
concat to combine strings
lpad to place a leading 0 if month is one digit
and uses extract to pick of the part of date needed.
working fiddle
http://sqlfiddle.com/#!2/63b24/8
DATEPART
It is a Datetime function which extract information from date. This function always returns result as integer type.
SELECT DATEPART(month, '2009-01-01 00:00:00:000') as month
it is return "1" as an integer:
DATENAME
It is also another Datetime function which to extract information from date. This function always returns result as varchar
SELECT DATENAME(month, '2009-01-01 00:00:00:000') as month
it is return "January".

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

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