简体   繁体   English

SQL语句DateTime格式

[英]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 1天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 我希望它输出信息,以便以小时为单位计算日期,因此基本上删除如下所示的“ 1d”

36:05:52 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 : 就像@Hadi在他的评论中说的那样,您可以在VB.Net中使用TimeSpan对象(您已经用这个标记了问题,因此似乎可以建议),但是您也可以使用这段SQL,我认为这是比其他建议稍微简单一些:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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