If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > ANSI SQL > MS Query Analyzer: how to calculate a time span with two DATETIMES?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 05-15-02, 22:43
Dylan Leblanc Dylan Leblanc is offline
Registered User
 
Join Date: May 2002
Location: Vancouver Canada
Posts: 26
MS Query Analyzer: how to calculate a time span with two DATETIMES?

Hi there, we have an assignment in school and one of the questions is to show the years of work experience that some nurses have.

I have figured out that if you have two columns that are the DATETIME datatype (which we have in the assignment), you can subtract one from another to get a date. I did a little test and it comes back as Jan xx 1900, where xx is the number of days.


I did this:

CREATE TABLE DateTest (

dateFrom DATETIME,
dateTo DATETIME

)

INSERT INTO DateTest VALUES ('april 17 2002', 'april 20 2002')




Which seems fine.

Then I went:

SELECT * FROM DATETEST


and got:

dateFrom dateTo
----------------------- -------------------------
2002-04-17 00:00:00.000 2002-04-20 00:00:00.000



Seems fair enough.

Then:

SELECT (dateTo - datefFom) AS timeSpan FROM DateTest

and got:

timeSpan
---------------------------
1900-01-04 00:00:00.000


So you see how it comes back as Jan 4th, to indicate the 4 days.

How can I get it to come back as simply 4 days? Is this supported???

Thanks for your help!
Reply With Quote
  #2 (permalink)  
Old 05-16-02, 05:13
alligatorsql.com alligatorsql.com is offline
Registered User
 
Join Date: Jul 2001
Location: Germany
Posts: 189
Hello,

one way is to cast the result into int. Use something like this:

SELECT CAST(datefrom-dateto AS INT) FROM ....

Hope that helps ?

Regards
Manfred Peter
(Alligator Company)
http://www.alligatorsql.com
Reply With Quote
  #3 (permalink)  
Old 05-16-02, 08:40
MattR MattR is offline
Registered User
 
Join Date: Mar 2001
Location: Lexington, KY
Posts: 606
Take a look at DATEDIFF and DATEPART functions in t-sql.
__________________
Thanks,

Matt
Reply With Quote
  #4 (permalink)  
Old 05-16-02, 14:53
Dylan Leblanc Dylan Leblanc is offline
Registered User
 
Join Date: May 2002
Location: Vancouver Canada
Posts: 26
Hi guys, thanks alot! The datediff function works perfectly! I like the ability to specify the time unit, like year, month, day, etc.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On