简体   繁体   中英

Get HH:MM:SS from a datetime in MSSQL

I have the following issue:

I have a datetime field, which contains entries like this: "1970-01-01 22:09:26.000"

I would like to extract only the 22:09:26 (hh:mm:ss) part, but I am unable to convert it into 24h format, I used FORMAT and CONVERT, but received the the am/pm culture (for the CONVERT I tried to use 13 culture value).

What is the simplest way to construct the formula to give back the above mentioned format?

Thank you!

To get just the time portion of a datetime you just need to cast or convert it into the appropriate data type. If you really want to be formatting your data right in the query, this is very possible with format and I am not sure what issues you were facing there:

declare @t table(d datetime);
insert into @t values(dateadd(minute,-90,getdate())),(dateadd(minute,-60,getdate())),(dateadd(minute,-30,getdate())),(dateadd(minute,90,getdate()));

select d
      ,cast(d as time) as TimeValue
      ,format(d,'HH:mm:ss') as FormattedTimeValue
from @t;

Output

+-------------------------+------------------+--------------------+
|            d            |    TimeValue     | FormattedTimeValue |
+-------------------------+------------------+--------------------+
| 2020-08-10 11:51:15.560 | 11:51:15.5600000 | 11:51:15           |
| 2020-08-10 12:21:15.560 | 12:21:15.5600000 | 12:21:15           |
| 2020-08-10 12:51:15.560 | 12:51:15.5600000 | 12:51:15           |
| 2020-08-10 14:51:15.560 | 14:51:15.5600000 | 14:51:15           |
+-------------------------+------------------+--------------------+

1st way You can select the format you wish from https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/

select replace(convert(nvarchar(20), CAST('1970-01-01 22:09:26.000' AS datetime), 114),'-',':')

2nd way It is not a conversion,but if your entries are all the same format then you can use the below:

select right('1970-01-01 22:09:26.000',12)

Updated if you have null dates as well:

1.

select case when value is not null
        then replace(convert(nvarchar(20), CAST(value AS datetime), 114),'-',':')
            else null
       end
select case when value is not null then right(value,12)
     else null end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM