42

How to convert datetime value to yyyymmddhhmmss?

for example From 2014-04-17 13:55:12

To 20140417135512

1

8 Answers 8

74

Since SQL Server Version 2012 you can use:

SELECT format(getdate(),'yyyyMMddHHmmssffff')
Sign up to request clarification or add additional context in comments.

1 Comment

This simplifies my life so much!
22

This seems to work:

declare @d datetime
set @d = '2014-04-17 13:55:12'

select replace(convert(varchar(8), @d, 112)+convert(varchar(8), @d, 114), ':','') 

Result:

20140417135512

Comments

9
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

Comments

7

FORMAT() is slower than CONVERT(). This answer is slightly better than @jpx's answer because it only does a replace on the time part of the date.

Format 112 = yyyymmdd - no format change needed

Format 108 = hh:mm:ss - so replace is used to remove the :

SELECT CONVERT(VARCHAR, GETDATE(), 112) + 
       REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '')

Comments

0

Another option I have googled, but contains several replace ...

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

Comments

0

This query is to convert the DateTimeOffset into the format yyyyMMddhhss with Offset. I have replaced the hyphens, colon(:), period(.) from the data, and kept the hyphen for the seperation of Offset from the DateTime.

SELECT REPLACE(SUBSTRING(CONVERT(VARCHAR(33),SYSDATETIMEOFFSET(),126), 1, 8), '-', '') +
SUBSTRING(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(33), SYSDATETIMEOFFSET(), 126),'T',''),'.',''),':',''),9,DATALENGTH(CONVERT(VARCHAR(33), SYSDATETIMEOFFSET(), 126)))

Comments

0

also this works too

SELECT replace(replace(replace(convert(varchar, getdate(), 120),':',''),'-',''),' ','')

Comments

0

20090320093349

SELECT CONVERT(VARCHAR,@date,112) + 
LEFT(REPLACE(CONVERT(VARCHAR,@date,114),':',''),6)

1 Comment

Code-only answers are considered low-quality. Your answer is likely to be deleted if you don't edit it so as to add an explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.