简体   繁体   中英

How to add and subtract hours in SQL Server 2005?

I want to add 24 format hours then result would be either 24 format or 12 format hours as per my requirement I will use two functions

This is my example

add ('08:05'+'02:00') result is 10:05

now again I want to convert the above result into 12 hour format so as per my result it would be 10:05 AM or 10:05

You may use the DateAdd function to do this, eg Dateadd(hour,2, @yourTime) .
To display the result, you can use the convert function. The convert function has many format options, so pick the one that suits your needs (I guess '0' would be ok).

Example:

select convert(varchar, dateadd(hour,2,myTimeColumn),0) as PlusTwoHours 
 from myTable. 

Hint: Avoid formatting in SQL. I would suggest removing the convert part and do the formatting in your application (report engine, excel or whatever).

DECLARE @TimeValueA as DateTime
DECLARE @TimeIncrementHours as int

SET @TimeValueA = '10:05:000'

SET @TimeIncrementHours  = 2


SELECT dateadd(hour,@TimeIncrementHours, @TimeValueA)

To Check and see if the time is 12 hour or 24 hour use the CONVERT function to a varchar like this:

FOR 24 hr

SELECT CONVERT(varchar, dateadd(hour,@TimeIncrementHours, @TimeValueA),108)

OR 12 hr

SELECT CONVERT(varchar(20), dateadd(hour,@TimeIncrementHours, @TimeValueA),100)

IN the Case where you want to add two DateTime's

SELECT CONVERT(datetime, '10:00:000') + CONVERT(datetime, '2:10:000')

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