tags:

views:

759

answers:

7

I have the following TSQL query to get date time value different:

SELECT CONVERT(DATETIME, EndDtField - StartDtField, 120) AS Duration
  FROM myTable;

The result will be:

  Duration
  1900-01-01 23:02:04.000
  ....

I tried to get partial string from the result like this '01 23:02:04.000' by using RIGHT() function (actually preferably in the format of '01 23:02:04' without 000):

SELECT RIGHT(CONVERT(DATETIME, EndDtField - StartDtField, 120), 15) AS Duration
  FROM myTable;

The result is:

 Duration
 1 1900 11:02PM
 ...

It looks like that the value of RIGHT(..) is a datetime value. Even I specify the datetime value in a format of yyyy-mm-dd hh:mi:ss but still I cannot get my expected result. How can I get a partial string with only day and time(dd hh:mi:ss) out from the Duration? I really don't like to parse out day, hour, minute and second values and then to build a string. Any other alternatives?

+3  A: 

There are SQL functions that do things similar to what you're trying:

DatePart will get a specific part of a date. So you could use this with your Duration field to format it however you like.

DateDiff will get the difference between two dates. you may be able to replace the entire subtraction with this.

Tom Ritter
Those functions are good but as I understand that, I still have to call 4 DatePart to build a partial string (day, hour, minute and second).
David.Chu.ca
+1  A: 
Joel Coehoorn
A: 

Try converting to varchar() before applying RIGHT()

Dan Sydner
no luck. I tried.
David.Chu.ca
+4  A: 

You probably need the following T-SQL:

SELECT RIGHT(CONVERT(VARCHAR, EndDtField - StartDtField, 121), 15) AS Duration FROM myTable;
Sergey Olontsev
This is what I want. It works! Thank you Sergey!
David.Chu.ca
when using CONVERT with date format 121, you can use char(23), which is the exact length needed. "varchar" without a length will be varchar(30)
KM
Great. I don't know that varchar is varchar(30) by default. Thanks for your information. Not sure if that default can be customized or not on sql server.
David.Chu.ca
+1  A: 

Off the top of my head the easiest way to do this is to do your calculation twice and then concatenate the two strings. This can be performed in a single select statement.

-- example
select cast(day(getdate()) as varchar) + ' ' + convert(varchar, getdate(), 108)

-- your code
SELECT cast(day(EndDtField - StartDtField) as varchar) + ' ' +
       convert(varchar, EndDtField - StartDtField, 108) AS Duration
  FROM myTable;
ahsteele
A: 

try this

SELECT CAST(DATEPART(DAY,(EndDtField  - StartDtField)) AS VARCHAR)+' '+CAST(DATEPART(HOUR,(EndDtField  - StartDtField)) AS VARCHAR)+':'+CAST(DATEPART(MINUTE,(EndDtField  - StartDtField)) AS VARCHAR)+':'+CAST(DATEPART(SECOND,(EndDtField  - StartDtField)) AS VARCHAR)
  FROM myTable;

Bye

RRUZ
A: 

Convert(DateTime,Convert(char,GetDate(),101),101)

Yasir Mehmood