Take the time from the datetime and convert it into seconds?

喜欢而已 提交于 2020-01-01 08:50:06

问题


I am running SQL Server 2005. Technically I know how to take the time from a tsql datetime.

CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond

The problem is that I have a datetime field and I need to essentially grab the time portion convert that to an integer specifically seconds. Then I need to do a bunch of arithmetic on this integer that I won't discuss here. I have searched on stackoverflow and haven't found a question that is specific to this question. Any ideas? I am really looking for best practices here, I am worried about creating a udf for this specific purpose as it completely throws the query optimizer out the window.

I have seen this webpage so please don't paste this. :

http://forums.devx.com/showthread.php?171561-TSQL-Converting-HH-MM-SS-to-seconds


回答1:


Use DATEPART:

(DATEPART(HOUR, GETDATE()) * 3600) +
(DATEPART(MINUTE, GETDATE()) * 60) +
(DATEPART(SECOND, GETDATE()))



回答2:


Just my 2 cents ...another way of doing this

Edit: Added method for SQL Server 2005 (Thank you Michael)

for SQL Server 2008

SELECT DATEDIFF(SECOND, CONVERT(date, GETDATE()), GETDATE())

for sql server 2005+

SELECT DATEDIFF(SECOND, DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())), GETDATE())



回答3:


The functions you want is DatePart

Declare @d DateTime
Select @d = GetDate()
Select (DatePart(HOUR, @d) * 3600) + (DatePart(MINUTE, @d) * 60) + DatePart(SECOND, @d)


来源:https://stackoverflow.com/questions/12415715/take-the-time-from-the-datetime-and-convert-it-into-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!