How to minus one hour from datetime value

  • Hi all,

    I have a variable @tothr of datatype datetime. I want to minus one hour if hour is not less than 4.

    Ex: if it contains value '1900-01-01 08:44:00.000' then i want to minus one hour from this value.

    Then it has to be '1900-01-01 07:44:00.000'

    if the value is '1900-01-01 03:44:00.000' it has to kept as it is.

    How to solve this issue.

    Thanking u all

    Sachin

  • Check this

    DECLARE @Date1datetime

    SET @Date1='1900-01-01 09:44:00.000'

    SELECT CASE

    WHEN DATEPART(hh,@Date1)>4

    THEN DATEADD(hh,-1,@Date1)

    ELSE

    @Date1

    ENDAS DATE1

  • Sachin , this will help you

    SELECT

    CASE WHEN DATEPART (HH,GETDATE()) < 4 THEN DATEADD(HH,-1, GETDATE())

    ELSE GETDATE()

    END [TIME]

    FROM TABLE A

  • Just use dateadd function. Use the parameters hh to specify that you want to use hours and -1 as the amount of hours that you want to add. You can read more about this function in Books On Line.

    Adi

    edited - Sorry, I didn't understand the question, and my answer was not a good one.

    --------------------------------------------------------------
    To know how to ask questions and increase the chances of getting asnwers:
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    For better answers on performance questions, click on the following...
    http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • Thank you both Gopi and coldcoffee for your answers.

    sachin

  • You're welcome, sachin!

    😎

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply