We help IT Professionals succeed at work.

Subtract two dateTime fields

1,122 Views
Last Modified: 2012-05-06
How do I two subtract a DateTime fields in sql
Feild1 = 2009/04/05 08:00, Field2 = 2009/05/02 09:00
The dates should not be counted in the subtraction. The value to be returned should be 01:00.
Comment
Watch Question

Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Top Expert 2010
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Top Expert 2010

Commented:
The "round trip" CONVERT expressions have the effect of stripping the date portions of the datetime values;
similarly, had I used the format code 101 instead of 108, it would have stripped the time portions.

Author

Commented:
matthewspatrick:
The CONVERT is not stripping the date properly. Im getting 12/31/1899 & 01/01/1900

Author

Commented:
If I have a time Value of 08:00 AM & 07:00 PM I would like a value of 12:00 returned with no AM / PM.
Will the Convert approach do this for me ?
CERTIFIED EXPERT
Top Expert 2010

Commented:
u2envy1,

datetime values always encode a date and a time.  To enforce formatting:

SELECT Field1, Field2, CONVERT(varchar, CONVERT(datetime, CONVERT(varchar, Field2, 108)) - CONVERT(datetime, CONVERT(varchar, Field1, 108)), 108) AS Diff
FROM SomeTable

Regards,

Patrick

Author

Commented:
Thx Matthew.....
How do I convert the As Diff to show hh:mm only. No seconds ?
CERTIFIED EXPERT
Top Expert 2010
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Thx, its working perfectly......

Author

Commented:
One more thing. Is it possible to Sum(Diff) ?
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.