简体   繁体   中英

SQL statement DateTime format

I am looking for some help in regards to the format that I want my data outputted.

Below is a snippet of the code I am using. It is currently converting the value from the database in seconds and outputting it like

1d 12:05:52

I want it to output the information so it calculates the day in the hours, so basically dropping the '1d' like below

36:05:52

CAST(FLOOR([Running] / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(8), DATEADD(SECOND, [Running], '19000101'), 8) AS [Running]

Can someone please point me in the right direction using the code above?

Thanks in advance for your help.

This should work:

SELECT 
    CASE WHEN [Running]/3600 <= 9 THEN '0' ELSE '' END + 
    CONVERT(VARCHAR(10),[Running]/3600)+':'+
    RIGHT('00'+CONVERT(VARCHAR(2),([Running]%3600)/60),2)+':'+
    RIGHT('00'+CONVERT(VARCHAR(2),[Running]%60),2) AS [Running]

I tested it using this:

DECLARE @Running int
SET @Running = 60*60*24*30 + 60*3 + 3 -- should output 720:03:03
SELECT
    CASE WHEN @Running/3600 <= 9 THEN '0' ELSE '' END +
    CONVERT(VARCHAR(10),@Running/3600)+':'+
    RIGHT('00'+CONVERT(VARCHAR(2),(@Running%3600)/60),2)+':'+
    RIGHT('00'+CONVERT(VARCHAR(2),@Running%60),2) AS [Running]

Output:

Running
----------------
720:03:03

(1 row(s) affected)

As @Hadi said in his comment, you can use the TimeSpan object in VB.Net (you've tagged the question with this so it seems reasonable to suggest), but you could also use this bit of SQL instead, which I think is slightly simpler than the other suggestion :

CAST(CAST(FLOOR([Running] / 3600) AS INT) AS VARCHAR) + 
RIGHT(CONVERT(VARCHAR, DATEADD(SECOND, [Running], '1900-01-01'), 108), 6) as [Running]

Here's one more way to do it, good answers here already tho. :)

-- Setting param for testing purposes, replace this with actual column in the formula below
DECLARE @SECS INT
SET @SECS = 3787*26

-- Your original formula for 'D' value
SELECT CAST(FLOOR(@SECS / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(8), DATEADD(SECOND, @SECS, '19000101'), 8)

-- New one for HH:MM:SS
SELECT CAST(@SECS/3600 AS VARCHAR(20))+':'+RIGHT('0'+CAST((@SECS%3600)/60 AS VARCHAR(2)),2)+':'+RIGHT('0'+CAST(@SECS%60 AS VARCHAR(2)),2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM