Convert hh:mm:ss to hh:mm in SQL Server - sql-server

I have time as 04:02:00, I want it only as 4:02 using SQL Server
I have tried this code:
#time time
set #time ='04:02:00'
SELECT RIGHT(convert(varchar, #time, 100), 8)
It produces output:
4:02AM
please help ..
Thanks

You can use:
DECLARE #dt DATETIME
SET #dt = GETDATE()
SELECT CONVERT(varchar(5),#dt,108)
This query gives result in the format 'HH:mm'.
Hope it helps.

DECLARE #time datetime
set #time ='04:02:00'
SELECT LEFT(RIGHT(convert(varchar, #time, 100), 8), 6)

You can use DATEPART and concatenate from there:
SELECT
RIGHT('00' + CONVERT(VARCHAR(2), DATEPART(HOUR, #time)), 2) + ':'
+ RIGHT('00' + CONVERT(VARCHAR(2), DATEPART(MINUTE, #time)), 2)
Notice the RIGHT('00' + ..., 2), this is to pad the hour or minute part with leading zeroes so that it'll be two characters long, e.g 4 becomes 04.

Related

Time difference with hours, minutes and seconds in SQL Server

I need to find time difference between two columns with hours, minutes and seconds.
These are two datetime columns in my table:
STOP_TIME Start_Time
------------------------------------------------------
2016-05-10 03:31:00.000 2016-05-10 02:25:34.000
I calculated second difference for stoptime and starttime. 3926 is the second difference.
I need to convert this to time format hh:mm:ss.
This should work for you -
DECLARE #STOP_TIME DATETIME = '2016-05-10 03:31:00.000',
#Start_Time DATETIME = '2016-05-10 02:25:34.000'
SELECT
RIGHT('0' + CAST(DATEDIFF(S, #Start_Time, #STOP_TIME) / 3600 AS VARCHAR(2)),2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, #Start_Time, #STOP_TIME) % 3600/60 AS VARCHAR(2)),2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, #Start_Time, #STOP_TIME) % 60 AS VARCHAR(2)),2)
Sql server supports adding and subtracting on Datetime data type, so you can simply do something like this:
DECLARE #StartTime datetime = '2016-05-10 02:25:34.000',
#EndTime datetime = '2016-05-10 03:31:00.000'
SELECT CAST(#EndTime - #StartTime as Time) As TimeDifference
Result: 01:05:26
Note: As TT rightfully wrote in his comment, casting to time will only work if the difference between #EndTime and #StartTime is less then 24 hours.
If you need to compare times that are further apart, you need to use one of the other solutions suggested.

Format short int to time in SQL Server

I have a time column showing up as an int. 800 would be 08:00am and 1300 would be 1:00pm.
How can I format the int so that it appears as 12h time, e.g. 1:13 pm?
I'm using SQL Server.
Thanks
You can do something like below to achieve the required result. Idea taken from How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?
set #time = 1300
select (#time / 1000000) % 100 + ':' +
(#time / 10000) % 100 + ':' +
(#time / 100) % 100 + ':' +
(#time % 100) * 10
Convert the integer to hh:mm:ss representation of datetime and handle formatting (i.e. AM/PM) in the presentation layer:
DECLARE #Time INTEGER = 800;
SELECT
-- convert datetime to hh:mm:ss
CONVERT(VARCHAR,
-- cast hh:mm to datetime
CAST(-- insert semicolon to get hh:mm format
STUFF(-- convert integer to string and pad with zeroes
RIGHT(REPLICATE('0', 4) + CAST(#Time AS VARCHAR), 4),
3, 0, ':')
AS DATETIME),
108);
SELECT #Time = 1300;
SELECT CONVERT(VARCHAR, CAST(STUFF(RIGHT(REPLICATE('0', 4) + CAST(#Time AS VARCHAR), 4), 3, 0, ':') AS DATETIME), 108);
Example selecting from temporary table:
CREATE TABLE #Time ( TimeValue INTEGER );
INSERT INTO #Time VALUES (800);
INSERT INTO #Time VALUES (1300);
SELECT CONVERT(VARCHAR,
CAST(STUFF(RIGHT(REPLICATE('0', 4) + CAST(TimeValue AS VARCHAR), 4),
3, 0, ':')
AS DATETIME), 108) AS Time
FROM #Time;
DROP TABLE #Time;

Convert decimal time to hours and minutes

Been struggling with this and can't seem to find the right answer, although there are plenty of mentions for converting, but nothing specific is working.
I need to convert a time with data type of float into hours and minutes. So 13.50 as 13.30. The data type as fixed as float in DB so cannot change. DB is SQL Server 2008R2
Have tried:
cast(cast(floor(fdsViewTimesheet.perStandardHours) as
float(2))+':'+cast(floor(100*(
fdsViewTimesheet.perStandardHours - floor(fdsViewTimesheet.perStandardHours)))as
float(2)) as time) AS STANDARD_HOURS
But I get error message "Explicit conversion from data type real to time is not allowed" Have tried as char instead of as float but query hangs.
What am I doing wrong? I just want to convert a float value into hours and minutes.
Would be grateful if someone could point me in the right direction.
You can try:
DECLARE #HOURS decimal(7,4) = 20.5599
SELECT CAST(CONVERT(VARCHAR,DATEADD(SECOND, #HOURS * 3600, 0),108) AS TIME)
output : 20:33:35
But remember : Type Time in MSSQL only under 24hrs
If you want greater than 24hrs, try:
DECLARE #HOURS decimal(7,4) = 25.5599
SELECT
RIGHT('0' + CAST (FLOOR(#HOURS) AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST(FLOOR((((#HOURS * 3600) % 3600) / 60)) AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST (FLOOR((#HOURS * 3600) % 60) AS VARCHAR), 2)
output : 25:33:35
-- Update
Decimal minutes to more than 24hrs
DECLARE #MINUTES decimal(7,4) = 77.9
SELECT
RIGHT('0' + CAST (FLOOR(COALESCE (#MINUTES, 0) / 60) AS VARCHAR (8)), 2) + ':' +
RIGHT('0' + CAST (FLOOR(COALESCE (#MINUTES, 0) % 60) AS VARCHAR (2)), 2) + ':' +
RIGHT('0' + CAST (FLOOR((#MINUTES* 60) % 60) AS VARCHAR (2)), 2);
output: 01:17:54
This should work for you
DECLARE #f [real]
SET #f = 13.50
SELECT DATEADD(mi, (#f - FLOOR(#f)) * 60, DATEADD(hh, FLOOR(#f), CAST ('00:00:00' AS TIME)))
DECLARE #f FLOAT = 13.5;
SELECT CONVERT(TIME(0), DATEADD(MINUTE, 60*#f, 0));
Or if you just want hh:mm as a string:
SELECT CONVERT(CHAR(5), DATEADD(MINUTE, 60*#f, 0), 108);
Just be careful if you have values >= 24.
How about you convert to minutes and add to the 00:00 time like so:
DECLARE #c datetime
select #c = dateadd(mi,fdsViewTimesheet.perStandardHours*60,'00:00')
If you wanted to do it in the statement with Time only:
select CONVERT(TIME,dateadd(mi,fdsViewTimesheet.perStandardHours*60,'00:00') )
If you have values that are larger than 24 hours, then the standard datetime and time types in sql cannot hold these. They are limited to holding 24 hour ranges.
What you would need to do is store the time representation in a string for example like so:
select cast(floor(fdsViewTimesheet.perStandardHours) as varchar(10)) + ':' + cast(FLOOR( (fdsViewTimesheet.perStandardHours - floor(fdsViewTimesheet.perStandardHours))*60)as varchar(2))

Date format in dd/MM/yyyy hh:mm:ss

I need to convert datetime from 2012-07-29 10:53:33.010 to
29/07/2012 10:53:33.
I tried using
select CONVERT(varchar(20), GETDATE(), 131)
but its showing date according to Hijri calendar
11/09/1433 10:53:33:
Please help?
SELECT FORMAT(your_column_name,'dd/MM/yyyy hh:mm:ss') FROM your_table_name
Example-
SELECT FORMAT(GETDATE(),'dd/MM/yyyy hh:mm:ss')
This can be done as follows :
select CONVERT(VARCHAR(10), GETDATE(), 103) + ' ' + convert(VARCHAR(8), GETDATE(), 14)
Hope it helps
You could combine 2 formats:
3 dd/mm/yy (British/French)
8 hh:mm:ss
according to CONVERT() function, and using + operator:
SELECT CONVERT(varchar(10),GETDATE(),3) + ' ' + CONVERT(varchar(10),GETDATE(),8)
SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)
The chapter on CAST and CONVERT on MSDN Books Online, you've missed the right answer by one line.... you can use style no. 121 (ODBC canonical (with milliseconds)) to get the result you're looking for:
SELECT CONVERT(VARCHAR(30), GETDATE(), 121)
This gives me the output of:
2012-04-14 21:44:03.793
Update: based on your updated question - of course this won't work - you're converting a string (this: '4/14/2012 2:44:01 PM' is just a string - it's NOT a datetime!) to a string......
You need to first convert the string you have to a DATETIME and THEN convert it back to a string!
Try this:
SELECT CONVERT(VARCHAR(30), CAST('4/14/2012 2:44:01 PM' AS DATETIME), 121)
Now you should get:
2012-04-14 14:44:01.000
All zeroes for the milliseconds, obviously, since your original values didn't include any ....
CREATE FUNCTION DBO.ConvertDateToVarchar
(
#DATE DATETIME
)
RETURNS VARCHAR(24)
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),#DATE, 121))
END
select DATE_FORMAT(NOW(),'%d/%m/%Y %h:%m:%s')
from dual
Try this wherever required, I have used this in JpaRepository in SpringBoot Project.
This will be varchar but should format as you need.
RIGHT('0' + LTRIM(DAY(d)), 2) + '/'
+ RIGHT('0' + LTRIM(MONTH(d)), 2) + '/'
+ LTRIM(YEAR(d)) + ' '
+ RIGHT('0' + LTRIM(DATEPART(HOUR, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(MINUTE, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(SECOND, d)), 2)
Where d is your datetime field or variable.

INT to hh:mm:ss tt in SQL Server

I will have an integer calculated from datediff()
let's say.. it is..
declare #earliestTime int;
set #earliestTime=50000000;
I want to convert to hh:mm:ss tt
I have this code to convert that int to HH:mm:ss
CONVERT(varchar(6), (#earliestTime)/60)+ ':' + RIGHT('0' + CONVERT(varchar(2), ((#earliestTime) % 60) ), 2)+ ':' + RIGHT('0' + CONVERT(varchar(2), ((#earliestTime) %60)*0), 2)
How can I modify it to hh:mm:ss tt (AM or PM)
I modified like this..
CONVERT(varchar(6),
case
when
((#earliestTime)/60)<=12
then
((#earliestTime)/60)
else
(((#earliestTime)/60)-12)
end )
--CONVERT(varchar(6), case when((#earliestTime)/60)<=12 then (#earliestTime)/60 else ((#earliestTime)/60)-12)
+
':'
+
RIGHT('0' + CONVERT(varchar(2), ((#earliestTime) % 60) ), 2)
+
':'
+
RIGHT('0' + CONVERT(varchar(2), ((#earliestTime) %60)*0), 2
+
' '
+
convert(varchar(2),(case when ((#earliestTime)/60)<12 then 'am' else 'pm' end)))
But it gives me this error..
Conversion failed when converting the
varchar value 'pm' to data type int.
I already convert 'pm' or 'am' to varchar(2). why the system still gives me that error?
How to make it correct or is there a better way?
You don't explain what your integer represents so it is difficult to give an answer.
It's best to use a proper data type for times. I'd use DATETIME - it will allow to you to perform calculations, sort, and format as required. Storing time as text is going to cause headaches later on.
Store a time by adding the time to the SQL epoch (1900-01-01 00:00:00), like so
SELECT DATEADD(SECOND, 50000, CONVERT(DATETIME, 0.0))
SELECT DATEADD(MINUTE, 50000, CONVERT(DATETIME, 0.0))
Then format the DATETIME object accordingly.
To get HH:mm:ss, use format 108.
To get the AM/PM flag, use 100 and take the two rightmost characters.
Try the below:
DECLARE #date DATETIME
SET #date = DATEADD(SECOND, 50000, CONVERT(DATETIME, 0.0))
SELECT CONVERT(VARCHAR, DATEPART(HOUR, #date)%12)
+ ':' + RIGHT(CONVERT(VARCHAR, #date, 108),5)
+ RIGHT(CONVERT(VARCHAR, #date, 100), 2)
I should also point out that you are working in a database, not a presentation layer. There should be no need to worry about formatting dates and times in a database; it is about data storage and retrieval. Presumably you are returning this time to an application or webpage to be put onto a screen, into a report or whatever - best practice is to keep the data as a complete DATETIME and let the top layer format it. By converting to a VARCHAR you are just removing information and limiting yourself; no benefit, lots of cost.

Resources