Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract minute from DateTime in SQL Server 2005

Suppose I have a datetime field whose value is 2000-01-01 08:30:00 and a duration field whose value is say 00:15 (meaning 15 minutes)

If I subtract these two, I should get 2000-01-01 08:15:00

Also if I want to subtract 1:15 (means 1 hour 15 minutes), the output should be 2000-01-01 07:15:00

I am trying SELECT DATEDIFF(minute, '00:15','2000-01-01 08:30:00');

But the output is 52595055. How can i get the desired result?

N.B.~ If I do SELECT dateadd(minute, -15,'2000-01-01 08:30:00'); , I will get the desired result but that involves parsing the minute field.

Edit:

As per the answers, every one is suggesting converting everything into minutes and then to subtract - so if it is 1:30, i need to subtract 90 minutes. That's fine. Any other way without converting to minutes?

like image 636
priyanka.bangalore Avatar asked Feb 22 '10 05:02

priyanka.bangalore


People also ask

How do I subtract minutes from a time in SQL?

Time subtraction: result = time1 - time2 If MINUTE( TIME2 ) <= MINUTE( TIME1 ) then MINUTE( RESULT ) = MINUTE( TIME1 ) - MINUTE( TIME2 ) . If MINUTE( TIME2 ) > MINUTE( TIME1 ) then MINUTE( RESULT ) = 60 + MINUTE( TIME1 ) - MINUTE( TIME2 ) and HOUR( TIME2 ) is incremented by 1.

Can I subtract time in SQL?

MySQL SUBTIME() FunctionThe SUBTIME() function subtracts time from a time/datetime expression and then returns the new time/datetime.

How do I subtract 1 date in SQL?

To get yesterday's date, you need to subtract one day from today's date. Use GETDATE() to get today's date (the type is datetime ) and cast it to date . In SQL Server, you can subtract or add any number of days using the DATEADD() function. The DATEADD() function takes three arguments: datepart , number , and date .

How do I subtract a date from a timestamp in SQL?

If you are using tSQL then you could use the DATEDIFF function. You can use this function with hours but if you want fractions of hours then you can use minutes and then convert back to hours. Since it is a calculated field, I would just create a view with the DATEDIFF function for the calculated field.


1 Answers

SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');  

The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like

SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');  

where @h is the hour part of your string and @m is the minute part of your string

EDIT:

Here is a better way:

SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime) 
like image 164
Martin Booth Avatar answered Sep 20 '22 13:09

Martin Booth