SQL Server How can I add Hour and minute in a single query

vql8enpb  于 2023-03-11  发布在  其他
关注(0)|答案(6)|浏览(178)

How can I add hours and minutes in a single query?

I tried this

Select DATEADD(hh,23.59,CAST('2016-07-08' AS DATETIME))

I need to ad 23 hours and 59 minutes, but my code only adds the hours. Why?

gzszwxb4

gzszwxb41#

How about this?

Select DATEADD(minute, 23*60 + 59, CAST('2016-07-08' AS DATETIME))

EDIT:

If you are getting a float/decimal value such as 23.59, then you can do:

Select DATEADD(minute, FLOOR(@hhmm) * 60 + (@hhmm - FLOOR(@hhmm)) * 100, CAST('2016-07-08' AS DATETIME))

Note: You can also use:

Select DATEADD(minute, FLOOR(@hhmm) * 60 + (@hhmm % 1) * 100, CAST('2016-07-08' AS DATETIME))

But I find this usage of the modulo operator slightly off-kilter.

mrwjdhj3

mrwjdhj32#

Use the below code for adding time part to a date.

SELECT DATEADD(Day, DATEDIFF(Day, 0, CAST('2016-07-08' AS DATETIME)), '23:59:00.000')

drkbr07n

drkbr07n3#

You can also use DATEADD() twice:

Select DATEADD(minute,59,DATEADD(hh,23,CAST('2016-07-08' AS DATETIME)))
epfja78i

epfja78i4#

The datepart argument, in your case hh , is part of date to which an integer number is added. So the DATEADD function just ignores any fractional part of your input.

To get result you want, you need to either use DATEADD twice, adding 23 hours and then 59 minutes, or add one day to your date and subtract 1 minute, like this:

Select DATEADD(MI, -1, CAST('2016-07-08' AS DATETIME) + 1)

See also Microsoft's documentation on DATEADD .

7cwmlq89

7cwmlq895#

another method : you can do by adding one day and then substract minute

Output is same

select DATEADD(minute, -1, DATEADD(DAY, 1,CAST('2016-07-08' AS DATETIME)))
yzuktlbb

yzuktlbb6#

In Oracle SQL I do it like this and it work fine to me

SELECT (NVL(TO_DATE (TO_CHAR (TIME_1, 'HH24:MI'), 'HH24:MI')
            - TO_DATE (TO_CHAR (TIME_2, 'HH24:MI'), 'HH24:MI'),
            0) * 24) * 60 in_min 
 FROM dual

相关问题