how to return difference in datetime values as a timespan

Hello,

DATEDIFF returns an integer, which I suppose I could use to build a
timespan string, but I'd like to avoid reinventing any wheels.  How do
I retun the difference in two datetime values as a "timespan" value
that won't completely confuse the report user?  To me, "02:14:37"
represents two hours, fourteen minutes, and 37 seconds.  For example,
what's the best way to determine the NapLength value in the following
query results?

DECLARE @NapTimes TABLE (
	  NapID INT
	, StartTime DATETIME
	, EndTime DATETIME
)

INSERT INTO @NapTimes SELECT 1, getdate(), dateadd(minute, 75,
getdate())
UPDATE @NapTimes SET EndTime = dateadd(second, 29, EndTime)

SELECT *, '1:15:29' AS NapLength FROM @NapTimes


0
new
9/2/2010 5:33:47 PM
sqlserver.programming 1873 articles. 0 followers. Follow

3 Replies
675 Views

Similar Articles

[PageSpeed] 22

Well it took me about .5 minutes to figure this out on my own.

declare @D1 datetime, @d2 datetime, @d3 time(0)

select @D1 = GETDATE(), @d2 = dateadd(hour, 2, GETDATE())
select @d2 = DATEADD(minute, 14, @d2)
select @d2 = DATEADD(second, 32, @d2)
select @d3 = @d2 - @d1

select @D1
select @d2
select @d3	--returns "02:14:32"
0
new
9/2/2010 6:00:44 PM
There is no build in function to do that.  You have to do your own.  There 
are lots of ways, for example

Select NapID, CONVERT(char(8), DATEADD(second, DATEDIFF(second, StartTime, 
EndTime), '19000101'), 114)
From @NapTimes;

Select NapID, LEFT(CAST(DATEADD(second, DATEDIFF(second, StartTime, 
EndTime), '19000101') As Time), 8)
From @NapTimes;

The first one works on any version of SQL, the second on SQL 2008 or later). 
They assume the time difference is less than 24 hours.  If you need to do 
this in lots of places, you might want to consider a user defined function.

But the best solution (IMO) is to just return the difference in seconds to 
your front end, and have your front end format it.  While you can use SQL to 
format data, it generally works beetter to do it in the front end.

Tom

"new DBA in '09" <ericbragas@gmail.com> wrote in message 
news:76f30cf1-24dc-40c3-a72f-7adf684d9eee@l20g2000yqm.googlegroups.com...
> Hello,
>
> DATEDIFF returns an integer, which I suppose I could use to build a
> timespan string, but I'd like to avoid reinventing any wheels.  How do
> I retun the difference in two datetime values as a "timespan" value
> that won't completely confuse the report user?  To me, "02:14:37"
> represents two hours, fourteen minutes, and 37 seconds.  For example,
> what's the best way to determine the NapLength value in the following
> query results?
>
> DECLARE @NapTimes TABLE (
>   NapID INT
> , StartTime DATETIME
> , EndTime DATETIME
> )
>
> INSERT INTO @NapTimes SELECT 1, getdate(), dateadd(minute, 75,
> getdate())
> UPDATE @NapTimes SET EndTime = dateadd(second, 29, EndTime)
>
> SELECT *, '1:15:29' AS NapLength FROM @NapTimes
>
> 

0
Tom
9/2/2010 6:07:55 PM
Thanks, Tom, that works stupendously.  I like your idea about the
formatting being done on the front end.  Especially considering that
my own solution above won't account for naps that actually span a date
change, but would end up giving a result like "21:46:32".  Which makes
me look bad.  Thanks for saving me the embarassment.
0
new
9/2/2010 6:38:23 PM
Reply:

Similar Artilces:

Zero-value Budget Column in FRx SP11
Hello all, We have just resolved an interesting problem that one of our customers was encountering after upgrading from FRx SP9 to SP11, that I'd like to share with you all, along with our resolution. Bear in mind, I am not recommending this resolution to you, so much as providing it to assist you with your own enquiries. The symptoms of the problem are as follows: A report contains a two columns, a budget column and an actuals column. Running the report on FRx SP9 produces the correct figures. Running the report on FRx SP11 produces correct actuals, but the budget figu...

Customer Returns
I'd like to know if there someone has written a RMS report that shows the customer account number, customer's name (last, first), and other customer statistics that INCLUDE pieces purchased and pieces returned. Or, if someone with more knowledge of SQL would care to share their coding expertise to accomplish the same, it would be appreciated. ...

Calendar-how do I keep a different background colour 4 each month
In process of doing a calendar for 2006. I want a different background color for each month, but everytime I change a color, it changes the background for every month. This is the first time I've used Publisher, but I simply can't find how to stabilise the page. Any tips would be great. Ungroup the objects, manually re-fill rather than using the color schemes. Time consuming but it works. -- Mary Sauer MSFT MVP http://office.microsoft.com/ http://msauer.mvps.org/ news://msnews.microsoft.com "frankie" <frankie@discussions.microsoft.com> wrote in message news:...

Return-Path: <> from Postmater
Hi, I got Exchange 2003 SP1 on Windows 2003 in Native Mode and when I receive bad mail the response is made from postmaster@mydomain.com but the return-path field is blank. With some anti-spam filter this Email is Junk. Return-Path: <> Anybody know how to specifeid a return-path to the NDR mail? _____________ Thank you Sebastien On Fri, 4 Nov 2005 12:48:04 -0800, "Sebas" <Sebas@discussions.microsoft.com> wrote: >Hi, > >I got Exchange 2003 SP1 on Windows 2003 in Native Mode and when I receive >bad mail the response is made from postmaster@mydomain.c...

Site for SOP Returns
Is it possible to have a different default Site ID for Returns than Standard Orders? Yes. You must make sure to change the site when performing a Return Transaction. -- Richard L. Whaley Author / Consultant / MVP 2006-2008 Documentation for Software Users Get our Free Tips and Tricks Newsletter and check out our books at http://www.AccoladePublications.com "Everton Raymond" wrote: > Is it possible to have a different default Site ID for Returns than Standard > Orders? Sorry, I did not see the word "default" in your post until after I r...

emial receive time different than system time
hi! I have a problem with my email received time stamp being different than the system time. The time stamp shows two hours earlier than when it was originally sent. This is on a windows 2000 machine. I am going crazy! trying to organize my email by received time. Can someone help me! thanks! I'm not sure, but you might want to check with your ISP. The time on THEIR system may be two hours before yours so it's showing it was received two hours earlier. Open one of the messages and then click on View and then Options. Check out the Internet Headers section which shows how the e...

.NET equivalent to XSLT value-of select
This seems like it should be really easy, but I cannot seem to make it work. I am trying to retrieve the text value of an element named "child2Element" from an XML file in a .NET (v 1.1) with an XPath expression. In an XSLT document I would use <xsl:value-of select="rootElement/child1Element[@childId='110']/child2Element"/> (and this does work fine in a transform). But I cannot seem to find the right method or object in .NET. There seem to be a number of classes that can use XPath, but I can't figure out which one I have to use to get just the te...

Query regarding A,B,C char. width values returned in 16-bit and 32-bit OS
I am trying to retrieve individual character widths of a string (from a TrueType font) and I tried using GetCharWidth (which weirdly works for TrueType fonts too tho' MSDN says otherwise) and/or GetCharABCWidths to retrieve the A,B and C spacings. Please note that I have selected the TrueType font (hFont) into the Device Context (hDC). I used GetCharABCWidths. Problem is this: GetCharABCWidths returns correct A,B and C widths in Win 98 and incorrect (much lesser A,B and C widths such that the characters OVERLAP) in other 32-bit OS (NT, XP). The effect is seen across all TrueType fonts, th...

Report for Returns
Anyone know a why to report on frequency of customer returns -- so we can see if any customers are making habit of this? Thanks and regards, Rich hitman, Try running a detailed sales report filtered to only negative sales displayed. Good luck, Matt "hitman" <hitman@discussions.microsoft.com> wrote in message news:0B3EE780-2655-45B4-B3C6-1F5D35FFA2A7@microsoft.com... > Anyone know a why to report on frequency of customer returns -- so we can > see > if any customers are making habit of this? > > Thanks and regards, > > Rich ...

Returning the Beginning of the week
Returning the beginning of the week. e.g. if the date == 02/03/04 (Friday 2nd March 2004) the beginning week for that date == 01/03/04 (Thursday 1st March 2004) Hows does one go about achieving this? Regards -- Rizitsu ------------------------------------------------------------------------ Rizitsu's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=15840 View this thread: http://www.excelforum.com/showthread.php?threadid=314968 This formula will take a date in cell A1 and give the start of the wee in B1 * assumes that monday is the start of the week, so i...

Deleting a note keeps the value in the NOTEINDX field
I just discovered that if you delete a note from a document (in my case, a cash receipts document), the system will delete the actual note record from the SY03900 table but will leave the original NOTEINDX value on the document record intact. Is this normal behavior? I would think the system should clear out the value in the document record since the note no longer exists. Referential integrity! -- Bud Cool, Accounting System Manager HDA, Inc. Hazelwood, MO GP 9.0, SP2 Yes, this is normal for GP. The record is created the first time the user clicks the note icon and "bookmarks...

return
Capability of the system to automatically change the status of the PO to change order, and add line items that have been returned. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" in the message pane. http://www.microsoft.com/Businesssolutions/Community/NewsGroups/dgbrowser/en-us/default.ms...

Different widths for each column in a 100% stacked column chart
I would like to present a chart that has 3 columns of data with each column being the same height and each column being split into different components (i.e. a 'typical' 100% stacked column chart). Each column represents a different market (split between the players in that particular market) and the markets are of diferent size. What I would like to do is make the width of each column vary depending on the size of the market. Effectively the height of the columns is the same and the vertical splits reflect the relative size of the components within each column but in additio...

form creating new row in table1, looking for field value in table
Please can someone help as I have been battling all week with this problem, and haven't had a response. I have a form which uses some data from table1 to create an entry in table2 (i know duplication is bad, but as this is a live database, and i am working on a new section, this makes this complicated task easier), which works fine. however, i have a third table that has the unique ID from table1 and table2 in order to show when a table1 row of data is needed in table2 via a checkbox. This third table3 is created when elsewhere. The problem lies with bringing in the unique ID value...

Return
When returning an item, can you return the item by selecting the matrix rather than the individual item and changing the quantity to -1? Hi KIm, Normally this won't work as it works in sale where for each matrix type you can put the qunatites. HOWEVER when you select the matrix item it bring the matrix window but allow only one item at a time to be returned and make the -1 qty automatically in return document type. It work but one by one. Regards Akber "Kim" wrote: > When returning an item, can you return the item by selecting the matrix > rather than the individua...

Returning Multiple Values in a Single Cell
Hello, I posted this same question a couple of weeks ago but forgot to mention a key point. My question was as follows: I have read a few posts regarding this subject but am still somewhat lost. I have a two sheet workbook (Excel 2000). On the first sheet is a list of projects that my department will complete during the year. A description of each project is given, a start date, an end date, as well as which crew will be completing the work (Crew 1 or Crew 2). What I am trying to do on the second sheet is to be able to type in any date, and have the description of the project on that da...

List of values summing to a known value
Is it possible to run a query that would return a list of values that sum to a known quantity. A simplified example would be as follows: Return any items from the list that sum to 10 1 3 4 7 9 The returned values would be 1,9 and 3,7. Thanks. Do you mean something like this -- SELECT [TableA_1].[Auto]+[TableA].[Auto] AS Expr1, TableA.Auto, TableA_1.Auto FROM TableA, TableA AS TableA_1 WHERE ((([TableA_1].[Auto]+[TableA].[Auto])=10)); -- Build a little, test a little. "lmattern" wrote: > Is it possible to run a query that would return a list...

Returns immediate function
Hi all, I know that the function CeRapiInitEx returns immediately. No wait for processing. I want to implement such a function. Returns immediate. no wait. How do I implement such a function? Thanks Ko You might create a UI thread that do the work, launch it in the "non-wait" function and return immediatly to the caller. When the thread done it's works, you can post an application message to return the results.... Greetings, Gaetano Sferra "PPC DEV" <ppc_dev@yahoo.com> ha scritto nel messaggio news:033101c3b388$a7098910$a301280a@phx.gbl... > Hi all...

Open Files from Different Versions
I have Publisher 2000 and upgraded to 6.0 recently but now I can't open old files created by 2000 but a different version. Can't find any info on the web site as far as a patch or conversion. Anyone have info? That is what was strange. Both the file and the software (under help, about) say 2000 but when I try to open the file it says it can't open different versions. I thought maybe there were different versions of 2000 (i.e. 5.0, 6.0, etc.) Our IT people upgraded the software from what I thought was 98 to 2000. If it was really 2002 then the software under help, ...

Opportunity status reason value
Hi, Does anyone know what table stores opportunity status reason value? I tried doing mail merge for email and i need that status reason value to be included. I tried using &opportunity.statuscode; however it returned the numerical value. Could someone help me on this? Thanks Carrie For picklists you always have two values: a numerical value and the text value. Where opportunity.statuscode returns the numerical value, opportunity.statuscodename should give you the text value. -- Matt Wittemann http://icu-mscrm.blogspot.com "Carrie" wrote: > Hi, > > Does an...

Lookup Values, return multiple.
I need help please. The formula I require has to in Worksheet A :- [B1] lookup DATA in Worksheet A [A1] SP001 in worksheet B [A] [B] [C] SP001 PL001 16 SP001 PL002 5 SP001 DR001 10 CR001 PL001 2 Search for all Text String starting with "PL" in Worksheet B [B] only for SP001 in [A] and return with values from Worksheet B [C] 16 and 5 I need the values to be seperated and not summed. Tx. Appreciate assistance. Try this... In the formulas: Rng1 refers to worksheet B $A$2:$A$5 Rng2 refers ...

Displaying only specified values-not using Autofilter
I have a somewhat unusual question based on something that's stumped me for over a week. I'm hoping the collective wisdom of this newsgroup might be of some help. I'm attempting to display all of the results of value "x" from one sheet on another. To elaborate, sheet 2 has a column, let's call it column A. Each cell in column A has a value, let's say, for simplicity sake, "1", "2", "3", or "4". What I want to do is go back to sheet 1 and format it in such a way that all of the rows containing value "1" in the afor...

% Return Line graph?
Hi- Can someone show me how to customize a graph in Money 2005 to show my stock portfolio's % change over time? I just want a simple line chart showing my percentage change since the beginning - as a way to just figure out relative performance but I can't seem to find the right graph to customize. I can't just chart the value of the portfolio as I have been adding money to it over time which has drastically changed the % returns. I am not sure if what I want is possible or if this is clear but I also have the plugin for MS Excel that I can import money data so if there is...

VLOOKUP & TWO DIFFERENT RANGES
Hello All, Can VLOOKUP lookup in two different different ranges residing in separate worksheettabs? In other words, if a match is not found in the first range then lookup the 2nd range. Can someone help in constructing such formula? Regards SJ one way =IF(ISNA(VLOOKUP(D1,Sheet1!A1:B11,2,FALSE)),VLOOKUP(D1,Sheet2!A1:B11,2,FALSE),VLOOKUP(D1,Sheet1!A1:B11,2,FALSE)) Mike "SSJ" wrote: > Hello All, > > Can VLOOKUP lookup in two different different ranges residing in separate > worksheettabs? In other words, if a match is not found in the first range > then...

How can I extract each Max key value ?
How can I extract the first entries for each key in Excel from the following 4 columns ? (i.e. the maximum value of cocatenated columns 1,2 &4 e.g. JohnSmith200). I already concatenated the first 2 columns as the key and SUMmed the "Values" for each key to create the "Running total" column. key & key Values Running total john smith 100 200 john smith 50 100 john smith 50 50 john thomas 50 50 bob jones 10 110 bob jones 100 100 I want: john smith 100 200 john smith 50 ...