SQL 如何将 nvarchar 转换为时间,而不是日期时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/838814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:58:41  来源:igfitidea点击:

how to convert nvarchar to time ,not datetime?

sqlsql-serversql-server-2005

提问by Penguen

DECLARE @DateNow smalldatetime
SET @DateNow='12:30'
select @DateNow
-------------------------------------OR--------------------------------------
select CAST( '12:30' as datetime )





Result: 1900-01-01 12:30:00.000 (i don't want this)

结果:1900-01-01 12:30:00.000(我不想要这个)


But i need this result in time format not string not datetime?


但是我需要时间格式而不是字符串而不是日期时间的结果?

Result: 12:30 (i want this)

结果:12:30(我想要这个)

回答by Andomar

Like José said, you can use CONVERT to display a datetime as date. MSDN has a list of all possible formats. For example format 8 is hh:mi:ss:

就像何塞所说,您可以使用 CONVERT 将日期时间显示为日期。MSDN 有一个所有可能格式的列表。例如格式 8 是 hh:mi:ss:

 select convert(varchar(32),getdate(),8)
 12:51:21

Now, you can cut the seconds off by specifying less characters:

现在,您可以通过指定更少的字符来缩短秒数:

 select convert(varchar(5),getdate(),8)
 12:51

Another often used format is 121, yyyy-mm-dd hh:mi:ss.mmm(24h):

另一种常用的格式是121,yyyy-mm-dd hh:mi:ss.mmm(24h):

 select convert(varchar(32),getdate(),121)
 2009-05-08 12:51:21.987

Where you can pick the time part like:

您可以在哪里选择时间部分,例如:

 select substring(convert(varchar(32),getdate(),121),12,5)
 12:51

Or to combine the string trickeries:

或者结合字符串技巧:

 select right(convert(varchar(16),getdate(),121),5)
 12:51

Right? Right!

对?对!

回答by Jose Basilio

There's a TIMEtype in SQL Server 2008, but in previous versions, you can represent it as a varchar for display.

SQL Server 2008 中有一个TIME类型,但在以前的版本中,您可以将其表示为 varchar 进行显示。

This is how you can retrieve the time portion of a DATETIME field in the format you want.

这是您如何以所需格式检索 DATETIME 字段的时间部分。

DECLARE @DateNow smalldatetime
SET @DateNow = GETDATE() -- 2009-05-08 12:58:02.680

SELECT CONVERT(CHAR(5), @DateNow, 8) 
-- this returns the time portion as 12:58

回答by Kirtan

You can use the CONVERTfunction.

您可以使用CONVERT函数。

By the way, there's no "TIME" datatype in SQL Server. So, the converted result will always be a STRING.

顺便说一下,SQL Server 中没有“TIME”数据类型。因此,转换后的结果将始终是 STRING。

EDIT: There's no "TIME" datatype in SQL Server versions <SQL Server 2008.

编辑:SQL Server 版本<SQL Server 2008 中没有“TIME”数据类型。

回答by M.Turrini

Ifyou need to compare, add and/or subtract time (only) values, think about the possibility to use a INT to store the "TIME" value and then to CONVERT it to CHAR when displaying the result.

如果您需要比较、添加和/或减去时间(仅)值,请考虑使用 INT 来存储“TIME”值,然后在显示结果时将其转换为 CHAR 的可能性。