Convert DDMMYYYY to YYYYMMDD date format in sql server?

喜夏-厌秋 提交于 2021-01-27 18:45:55

问题


I have a date in table as "26052016" in format DDMMYYYY I want to convert this date to "YYYYMMDD" format.

Any idea
I have tried this method

select CONVERT(varchar(8),[doc-date],112) FROM C034_PDK_ParallelBillingSourceExtract

But this is gives me the same date as a result.

Please help me


回答1:


I can find this way, i don't know if any other way exist or not..

declare @date nvarchar(max)='01052016'

select convert(varchar(8),cast(CONCAT(SUBSTRING(@date,3,2),'/',SUBSTRING(@date,1,2),'/',SUBSTRING(@date,5,4)) as date),112)as [YYYYMMDD]

Clear Code:

declare @date nvarchar(max)='01052016'
declare @date1 date
set @date1 =cast(CONCAT(SUBSTRING(@date,3,2),'/',SUBSTRING(@date,1,2),'/',SUBSTRING(@date,5,4)) as date)

select convert(varchar(8),@date1,112)as [YYYYMMDD]

If you are using Sql version< 2012 then you need to skip CONCAT and use + for string concatination.




回答2:


 SELECT CONVERT(VARCHAR(8), doc-date, 112) AS [YYYYMMDD] from
 C034_PDK_ParallelBillingSourceExtract

Check ... this should work correctly.

Thanks




回答3:


SELECT CONVERT(VARCHAR(8), '26052016', 112) AS [YYYYMMDD] from
 C034_PDK_ParallelBillingSourceExtract



回答4:


Try like this,

SELECT substring([doc-date], 5, 4) + substring([doc-date], 3, 2) + substring([doc-date], 1, 2) AS [YYYYMMDD]
FROM C034_PDK_ParallelBillingSourceExtract



回答5:


There are differet ways to do it.

The best way is to use substring method as you know the character positions are going to remain same.

For Example

Suppose your date is - 31122015

Pick the portions of date using substring method and concatenate them

select  SUBSTRING('31122015',5,4) + SUBSTRING('31122015',3,2) + SUBSTRING('31122015',1,2)

The result would be - 20153112




回答6:


Since SQL Server 2016 we have a couple of handy tools for this:

Use DATEFROMPARTS and SUBSTRING to convert odd date formats from any arrangement within a Varchar to an actual date:

SELECT DATEFROMPARTS(SUBSTRING('31122015',5,4), SUBSTRING('31122015',3,2), SUBSTRING('31122015',1,2))

Use FORMAT to Convert an actual date to YYYYMMDD:

SELECT FORMAT(MyDate, 'yyyyMMdd')

watch out for the yyyyMMdd, that's the only part of MS SQL that is case-sensitive. Lower case mm is "minutes" and upper case MM is "Month", upper case YYYY or DD is nothing, and will just add letters to your output!



来源:https://stackoverflow.com/questions/39138422/convert-ddmmyyyy-to-yyyymmdd-date-format-in-sql-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!