SQL Server:如何在 YYYYMMDDHHMISSMSS 中获取当前日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6802230/
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 11:26:51  来源:igfitidea点击:

SQL Server: How to get current date time in YYYYMMDDHHMISSMSS

sqlsql-servertsql

提问by riad

I need the current date time in the format YYYYMMDDHHMISSMIS

我需要格式的当前日期时间 YYYYMMDDHHMISSMIS

Example:

例子:

20110723233747607

By using the CURRENT_TIMESTAMPor getdate()functions, we can retrieve the current datetime into 2011-07-23 23:37:47.607format. If I use REPLACEand CONVERTfunctions to remove the "-" and ":" characters, then I get the value into

通过使用CURRENT_TIMESTAMPorgetdate()函数,我们可以将当前日期时间检索为2011-07-23 23:37:47.607格式。如果我使用REPLACECONVERT函数删除“-”和“:”字符,那么我将值放入

Jul 23 2011 11:37PM

...format. But I need the current date time as 20110723233747607to use it for my another purpose.

...格式。但是我需要当前的日期时间20110723233747607以将其用于我的另一个目的。

My SQL query is:

我的 SQL 查询是:

SELECT REPLACE(CONVERT(VARCHAR(20), CURRENT_TIMESTAMP),'.','')

output: Jul 23 2011 11:37PM

输出: Jul 23 2011 11:37PM

So how can I get the current date time in my required format? Pls help.

那么如何以我需要的格式获取当前日期时间?请帮忙。

回答by Mikael Eriksson

select replace(
       replace(
       replace(
       replace(convert(varchar(23), getdate(), 121),
       '-',''),
       '.',''),
       ' ',''),
       ':','')

回答by user007

I do not know why you need to use so many REPLACE() functions. Usage of functions really reduce the execution time. I used two CONVERT and one REPLACE function below.

我不知道你为什么需要使用这么多 REPLACE() 函数。函数的使用确实减少了执行时间。我在下面使用了两个 CONVERT 和一个 REPLACE 函数。

SELECT CONVERT(VARCHAR(8), GETDATE(), 112) + REPLACE(CONVERT(VARCHAR(12), GETDATE(), 114),':','')