SQL Server 2012 中的日期和时间格式转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22587617/
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
Date and Time Format Conversion in SQL Server 2012
提问by Nqabeni Simela
I am using SQL Server 2012 sp1 .I have a table column with the following Date Time values.
我正在使用 SQL Server 2012 sp1。我有一个包含以下日期时间值的表列。
BLDCHKDT
-----------------------
2013-06-19 00:00:00.000
2013-07-22 00:00:00.000
2013-08-21 00:00:00.000
2013-09-20 00:00:00.000
2013-11-18 00:00:00.000
I would like to retrieve the date and Time in the following formats:
我想以下列格式检索日期和时间:
Date: 19062013
Time: 00000000
Is it possible? I have reviewed the SQL Server help documentation for the FORMAT, CAST and CONVERT functions and I can't seem to get any headway. So far I have attempted the following conversions:
是否可以?我已经查看了 FORMAT、CAST 和 CONVERT 函数的 SQL Server 帮助文档,但似乎没有任何进展。到目前为止,我已经尝试了以下转换:
N.B Please note that I am converting to Date time to string to facilitate a flat file export.
NB 请注意,我正在将日期时间转换为字符串以方便平面文件导出。
--Retrieving Date
--检索日期
SELECT [DATE-BLDCHKD] = CONVERT (VARCHAR (20), BLDCHKDT, 112)
FROM TABLEA
DATE-BLDCHKD
--------------------
20130619
20130722
20130821
20130920
20131118
--Retrieving Time
SELECT [TIME-BLDCHKD] = CONVERT (VARCHAR (20), BLDCHKDT, 24)
FROM TABLEA
TIME-BLDCHKD
--------------------
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
I appreciate your insights. Thank you in advance.
我很欣赏你的见解。先感谢您。
回答by Hart CO
Since you're using SQL Server 2012 you can use the FORMAT()
function:
由于您使用的是 SQL Server 2012,您可以使用该FORMAT()
函数:
SELECT FORMAT(BLDCHKDT,'ddMMyyyy')
, FORMAT(BLDCHKDT,'hhmmssfff')
回答by Szymon
You can do it this way:
你可以这样做:
declare @value datetime = getdate()
select
replace(convert(varchar(20), @value, 104), '.', '') date_part,
left(replace(convert(varchar(20), @value, 114), ':', ''), 8) time_part
returns 23032014, 17174466 for 2014-03-23 17:17:44.660
2014-03-23 17:17:44.660 返回 23032014, 17174466
回答by GriGrim
Use 104th format for date part:
日期部分使用第 104 格式:
select replace (convert (varchar(10), @value, 104), '.', '') as date_part