sql server 2005 convert time to minutes [duplicate]

时光怂恿深爱的人放手 提交于 2019-12-11 06:34:07

问题


I have a few date time functions within my database, but I need to add one that takes the time portion of a datetime field and then converts the time into minutes

I have a function that get the minutes between two times, but not just the minutes of a single time.

 ALTER FUNCTION [dbo].[fn_MinutesBetween]
 ( @fStart datetime, @fEnd datetime )
 RETURNS int
 AS
 BEGIN
 RETURN DateDiff(minute, @fStart, @fEnd)

and another one that gets just the time portion

 ALTER function [dbo].[fn_ReturnTimeOnly]
 (@DateTime smallDateTime)
 returns nvarchar(50)
as
begin
  Return substring(cast(@DateTime as varchar),12,len(@DateTime))

end

How can I just get the minutes of the time. Like 1:00 am would be 60, 2:00 am would be 120 12:00 pm would be 720 etc.

Thanks


回答1:


I was given a link in comments to datetime to totalminute and used that to come up with a solution.

ALTER FUNCTION [dbo].[fn_ReturnMinutesOnly]
  ( @dt smalldatetime )

RETURNS int
AS
BEGIN
  RETURN DATEDIFF(MINUTE, DATEADD(DAY, DATEDIFF(DAY, 0, @dt), 0), @dt)
END



回答2:


Get the number of hours, cast to int, multiply by 60, get the number of mins, cast to int, add these two.

ALTER function [dbo].[fn_ReturnMinutesOnly]
 (@DateTime smallDateTime)
 returns INT
as
begin
        Return
            cast(substring(cast(@DateTime as varchar),13,2) as INT) * 60 +
            cast(substring(cast(@DateTime as varchar),16,2) as INT)
end



回答3:


Casting to string is expensive (I talk about the opposite scenario here, but the concept is the same). Try this instead:

DECLARE @DateTime DATETIME;
SET @DateTime = GETDATE();

SELECT DATEDIFF(MINUTE, DATEDIFF(DAY, 0, @DateTime), @DateTime);

In your function, this would be:

ALTER function [dbo].[fn_ReturnTimeOnly]
(@DateTime smallDateTime)
returns INT
as
begin
  Return (SELECT DATEDIFF(MINUTE, DATEDIFF(DAY, 0, @DateTime), @DateTime));
end


来源:https://stackoverflow.com/questions/15980219/sql-server-2005-convert-time-to-minutes

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