Pular para o conteúdo principal

Conversão de datas no MSSQL

Conversão de datas no MSSQL 

Fonte: https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/


How to get different date formats in SQL Server

  1. Use the SELECT statement with CONVERT function and date format option for the date values needed
  2. To get YYYY-MM-DD use this T-SQL syntax SELECT CONVERT(varchar, getdate(), 23)
  3. To get MM/DD/YY use this T-SQL syntax SELECT CONVERT(varchar, getdate(), 1)
  4. Check out the chart to get a list of all format options

Below is a list of SQL date formats and an example of the output.  The date used for all of these examples is "2022-12-30 00:38:54.840".

DATE ONLY FORMATS
Format #QueryFormatSample
1select convert(varchar, getdate(), 1)mm/dd/yy12/30/22
2select convert(varchar, getdate(), 2)yy.mm.dd22.12.30
3select convert(varchar, getdate(), 3)dd/mm/yy30/12/22
4select convert(varchar, getdate(), 4)dd.mm.yy30.12.22
5select convert(varchar, getdate(), 5)dd-mm-yy30-12-22
6select convert(varchar, getdate(), 6)dd-Mon-yy30 Dec 22
7select convert(varchar, getdate(), 7)Mon dd, yyDec 30, 22
10select convert(varchar, getdate(), 10)mm-dd-yy12-30-22
11select convert(varchar, getdate(), 11)yy/mm/dd22/12/30
12select convert(varchar, getdate(), 12)yymmdd221230
23select convert(varchar, getdate(), 23)yyyy-mm-dd2022-12-30
31select convert(varchar, getdate(), 31)yyyy-dd-mm2022-30-12
32select convert(varchar, getdate(), 32)mm-dd-yyyy12-30-2022
33select convert(varchar, getdate(), 33)mm-yyyy-dd12-2022-30
34select convert(varchar, getdate(), 34)dd-mm-yyyy30-12-2022
35select convert(varchar, getdate(), 35)dd-yyyy-mm30-2022-12
101select convert(varchar, getdate(), 101)mm/dd/yyyy12/30/2022
102select convert(varchar, getdate(), 102)yyyy.mm.dd2022.12.30
103select convert(varchar, getdate(), 103)dd/mm/yyyy30/12/2022
104select convert(varchar, getdate(), 104)dd.mm.yyyy30.12.2022
105select convert(varchar, getdate(), 105)dd-mm-yyyy30-12-2022
106select convert(varchar, getdate(), 106)dd Mon yyyy30 Dec 2022
107select convert(varchar, getdate(), 107)Mon dd, yyyyDec 30, 2022
110select convert(varchar, getdate(), 110)mm-dd-yyyy12-30-2022
111select convert(varchar, getdate(), 111)yyyy/mm/dd2022/12/30
112select convert(varchar, getdate(), 112)yyyymmdd20221230
 
TIME ONLY FORMATS
8select convert(varchar, getdate(), 8)hh:mm:ss00:38:54
14select convert(varchar, getdate(), 14)hh:mm:ss:nnn00:38:54:840
24select convert(varchar, getdate(), 24)hh:mm:ss00:38:54
108select convert(varchar, getdate(), 108)hh:mm:ss00:38:54
114select convert(varchar, getdate(), 114)hh:mm:ss:nnn00:38:54:840
 
DATE & TIME FORMATS
0select convert(varchar, getdate(), 0)Mon dd yyyy hh:mm AM/PMDec 30 2022 12:38AM
9select convert(varchar, getdate(), 9)Mon dd yyyy hh:mm:ss:nnn AM/PMDec 30 2022 12:38:54:840AM
13select convert(varchar, getdate(), 13)dd Mon yyyy hh:mm:ss:nnn AM/PM30 Dec 2022 00:38:54:840AM
20select convert(varchar, getdate(), 20)yyyy-mm-dd hh:mm:ss2022-12-30 00:38:54
21select convert(varchar, getdate(), 21)yyyy-mm-dd hh:mm:ss:nnn2022-12-30 00:38:54.840
22select convert(varchar, getdate(), 22)mm/dd/yy hh:mm:ss AM/PM12/30/22 12:38:54 AM
25select convert(varchar, getdate(), 25)yyyy-mm-dd hh:mm:ss:nnn2022-12-30 00:38:54.840
26select convert(varchar, getdate(), 26)yyyy-dd-mm hh:mm:ss:nnn2022-30-12 00:38:54.840
27select convert(varchar, getdate(), 27)mm-dd-yyyy hh:mm:ss:nnn12-30-2022 00:38:54.840
28select convert(varchar, getdate(), 28)mm-yyyy-dd hh:mm:ss:nnn12-2022-30 00:38:54.840
29select convert(varchar, getdate(), 29)dd-mm-yyyy hh:mm:ss:nnn30-12-2022 00:38:54.840
30select convert(varchar, getdate(), 30)dd-yyyy-mm hh:mm:ss:nnn30-2022-12 00:38:54.840
100select convert(varchar, getdate(), 100)Mon dd yyyy hh:mm AM/PMDec 30 2022 12:38AM
109select convert(varchar, getdate(), 109)Mon dd yyyy hh:mm:ss:nnn AM/PMDec 30 2022 12:38:54:840AM
113select convert(varchar, getdate(), 113)dd Mon yyyy hh:mm:ss:nnn30 Dec 2022 00:38:54:840
120select convert(varchar, getdate(), 120)yyyy-mm-dd hh:mm:ss2022-12-30 00:38:54
121select convert(varchar, getdate(), 121)yyyy-mm-dd hh:mm:ss:nnn2022-12-30 00:38:54.840
126select convert(varchar, getdate(), 126)yyyy-mm-dd T hh:mm:ss:nnn2022-12-30T00:38:54.840
127select convert(varchar, getdate(), 127)yyyy-mm-dd T hh:mm:ss:nnn2022-12-30T00:38:54.840
 
ISLAMIC CALENDAR DATES
130select convert(nvarchar, getdate(), 130)dd mmm yyyy hh:mi:ss:nnn AM/PMdate output
131select convert(nvarchar, getdate(), 131)dd mmm yyyy hh:mi:ss:nnn AM/PM10/12/1444 12:38:54:840AM

You can also format the date or time without dividing characters, as well as concatenate the date and time string:

Sample statementFormatOutput
select replace(convert(varchar, getdate(),101),'/','')mmddyyyy12302022
select replace(convert(varchar, getdate(),101),'/','') + replace(convert(varchar, getdate(),108),':','')mmddyyyyhhmmss12302022004426

If you want to get a list of all valid date and time formats, you could use the code below and change the @date to GETDATE() or any other date you want to use.  This will output just the valid formats.

DECLARE @counter INT = 0
DECLARE @date DATETIME = '2006-12-30 00:38:54.840'

CREATE TABLE #dateFormats (dateFormatOption int, dateOutput nvarchar(40))

WHILE (@counter <= 150 )
BEGIN
   BEGIN TRY
      INSERT INTO #dateFormats
      SELECT CONVERT(nvarchar, @counter), CONVERT(nvarchar,@date, @counter) 
      SET @counter = @counter + 1
   END TRY
   BEGIN CATCH;
      SET @counter = @counter + 1
      IF @counter >= 150
      BEGIN
         BREAK
      END
   END CATCH
END

SELECT * FROM #dateFormats

Postagens mais visitadas deste blog

REST Protheus Converter charset CP1252 para UTF8 com Header Accept UTF-8

O Protheus possui um tag que pode ser utilizada para conversão para UTF8 de forma transparente, basta enviar no header da requisição a TAG ACCEPT com charset=UTF-8, também pode-se adicionar o appllication/json. Accept : application/json; charset=UTF-8 ou Accept : charset=UTF-8 Isso ajuda pois não precisa mais utilizar as funções DecodeUTF8 e EncodeUT8 pois o próprio rest já vai fazer isso.

Recursividade Minha Linda! Estrutura Produtos Protheus SG1

Fato! Depois que você conhece recursividade em sua vida tudo fica mais leve (rss... ) a recursividade pode ser infinita (pode não ta!) se for infinita vai dar problema, não pode. Mas a recursividade nos ajuda a deixar nosso sistema mais flexível e dinâmico para montar uma série de regras de negócio. Hoje vou falar exatamente da SG1, tabela TOTVS Microsiga Protheus que é utilizada para montar a estrutura de um produto dentro PCP (Planejamento e Controle de Produção). Isso séria algo que a recursividade iria ajudar. Na SG1 temos o campos G1_COD (Pai) e G1_COMP (Filho). G1_COD->G1_COMP->G1_COD->G1_COMP->G1_COD->G1_COMP Seria assim o fluxo da informação. Sem mais delongas, abaixo vou deixar o script para MSSQL para apresentar esses dados. Inté! WITH ESTRUT( CODIGO, COD_PAI, COD_COMP, QTD, PERDA, DT_INI, DT_FIM ,TRT ,RECNO, NIVEL ) AS ( SELECT G1_COD PAI, G1_COD, G1_COMP, G1_QUANT, G1_PERDA, G1_INI, G1_FIM,G1_TRT,SG1.R_E_C_N_O_, 1 AS NIVEL FR

Cadastro de funções ADVPL

FWDirRemove( cDir, nType, lComplete, lKillFiles ) Função para remover diretórios, com a vantagem de remover somente o ultimo nível ou todo o caminho. cDir                   Diretório a ser removido lComplete          Remove todo o caminho (.T.) ou apenas o ultimo nível (.F.) lKillFiles             Remove os arquivos antes de tentar remover o diretório FWMakeDir( cDir, lShowMsg ) Função para criar diretório com seus subdiretórios, com a vantagem de criar todo o caminho. cDir                    Diretório a ser criado lShowMsg          Exibe ou não mensagem caso não consiga criar o diretório FwNoAccent( cString ) Retira acentos de uma string cString                 String a ser retirado os acentos Exemplo: cString := 'O avião não pôde aterrissar de manhã' cString := FwNoAccent( cString ) // Retorna : 'O aviao nao pode aterrissar de manha' FWGetSX5( cTable, cKey ) Função de retorno dos campos de uma tabela no SX5 cTable                  Tabela para pesquisa no SX5. Par