sql >> Base de Datos >  >> RDS >> Sqlserver

Varias formas de usar la función de fecha SQL CONVERT

En este artículo, exploraremos el uso de los diferentes formatos de fecha de SQL CONVERT dentro de SQL Server.

La interpretación de la fecha varía entre los diferentes países. Suponga que tiene una base de datos global de SQL Server con una tabla que contiene un formato de fecha específico. Por ejemplo, tiene una columna de fecha que tiene el valor 01/05/2020.

¿Cómo lo interpretas? Veamos las siguientes interpretaciones en diferentes países.

  • EE. UU.:5 de enero de 2020 (formato estándar:dd/mm/aaaa)
  • Europa:1 de mayo de 2020 (formato estándar:dd/mm/aaaa)

Además, otros países siguen diferentes formatos de fecha:

  • Turquía:dd.mm.yyyy
  • India:dd-mm-aaaa
  • Bulgaria:aaaa-m-d
  • Hungría:aaaa.mm.dd.

Puede consultar Wikipedia para obtener más información sobre los formatos de fecha por país.

Aparte de esto, a veces también queremos incluir la marca de tiempo junto con las fechas. Algunos ejemplos de esto son:

  • 05/01/2020 10:00
  • 05/0/2020 14:00
  • 05/05/2020 14:00
  • 05/01/2020 02:00:55

No es posible almacenar fechas en una tabla de SQL Server en diferentes formatos, por lo que necesitamos una forma de convertir formatos de fecha. Exploremos los diferentes métodos de formato de fecha de SQL CONVERT.

Función de fecha SQL CONVERT

Por lo general, los profesionales de bases de datos usan la función de fecha SQL CONVERT para obtener fechas en un formato específico y consistente. Esto aplica los códigos de estilo para fechas de salida específicas.

Sintaxis de la función CONVERT():

CONVERTIR (tipo de datos, fecha y hora [, estilo])

En la siguiente consulta SQL, convertimos la fecha y hora en dos formatos usando la función CONVERT().

  • formato mm/dd/aa:código de estilo 1
  • formato mm/dd/aaaa:código de estilo 101
DECLARE @Inputdate datetime = '2019-12-31 14:43:35.863';
Select CONVERT(varchar,@Inputdate,1) as [mm/dd/yy],
CONVERT(varchar,@Inputdate,101) as [mm/dd/yyyy]

Del mismo modo, podemos especificar diferentes códigos de estilo para que pueda convertir las fechas en su formato requerido.

SELECT '0' AS [StyleCode],
'Default format' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 0) AS [OutputFormat]
UNION ALL
SELECT '1' AS [StyleCode],
'USA - mm/dd/yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 1) AS [OutputFormat]
UNION ALL
SELECT '2' AS [StyleCode],
'ANSI - dd.mm.yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 2) AS [OutputFormat]
UNION ALL
SELECT '3' AS [StyleCode],
'British and French - dd/mm/yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 3) AS [OutputFormat]
UNION ALL
SELECT '4' AS [StyleCode],
'German - dd.mm.yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 4) AS [OutputFormat]
UNION ALL
SELECT '5' AS [StyleCode],
'Italian - dd-mm-yy ' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 5) AS [OutputFormat]
UNION ALL
SELECT '6' AS [StyleCode],
'Shortened month name -dd mon yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 6) AS [OutputFormat]
UNION ALL
SELECT '7' AS [StyleCode],
'Shortened month name - mon dd, yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 7) AS [OutputFormat]
UNION ALL
SELECT '8' AS [StyleCode],
'24 hour time -hh:mm:ss' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 8) AS [OutputFormat]
UNION ALL
SELECT '9' AS [StyleCode],
'Default + milliseconds - mon dd yyyy hh:mm:ss:mmmAM (or PM)' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 9) AS [OutputFormat]
UNION ALL
SELECT '10' AS [StyleCode],
'USA - mm-dd-yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 10) AS [OutputFormat]
UNION ALL
SELECT '11' AS [StyleCode],
'Japan -yy/mm/dd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 11) AS [OutputFormat]
UNION ALL
SELECT '12' AS [StyleCode],
'ISO format -yymmdd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 12) AS [OutputFormat]
UNION ALL
SELECT '13' AS [StyleCode],
'Europe default + milliseconds -dd mon yyyy hh:mm:ss:mmm' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 13) AS [OutputFormat]
UNION ALL
SELECT '14' AS [StyleCode],
' 24 hour time with milliseconds -hh:mm:ss:mmm(24h)' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 14) AS [OutputFormat]
UNION ALL
SELECT '20' AS [StyleCode],
'ODBC canonical -yyyy-mm-dd hh:mm:ss(24h)' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 20) AS [OutputFormat]
UNION ALL
SELECT '21' AS [StyleCode],
'ODBC canonical (with milliseconds) -yyyy-mm-dd hh:mm:ss.mmm' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 21) AS [OutputFormat]
UNION ALL
SELECT '22' AS [StyleCode],
'mm/dd/yy hh:mm:ss AM (or PM)' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 22) AS [OutputFormat]
UNION ALL
SELECT '23' AS [StyleCode],
'ISO 8601 - yyyy-mm-dd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 23) AS [OutputFormat]
UNION ALL
SELECT '100' AS [StyleCode],
'mon dd yyyy hh:mmAM' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 100) AS [OutputFormat]
UNION ALL
SELECT '101' AS [StyleCode],
'USA -mm/dd/yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 101) AS [OutputFormat]
UNION ALL
SELECT '102' AS [StyleCode],
'ANSI -yyyy.mm.dd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 102) AS [OutputFormat]
UNION ALL
SELECT '103' AS [StyleCode],
'British/French -dd/mm/yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 103) AS [OutputFormat]
UNION ALL
SELECT '104' AS [StyleCode],
'German - dd.mm.yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 104) AS [OutputFormat]
UNION ALL
SELECT '105' AS [StyleCode],
'Italian -dd-mm-yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 105) AS [OutputFormat]
UNION ALL
SELECT '106' AS [StyleCode],
'Shortened month name -dd mon yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 106) AS [OutputFormat]
UNION ALL
SELECT '107' AS [StyleCode],
'Shortened month name -mon dd, yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 107) AS [OutputFormat]
UNION ALL
SELECT '108' AS [StyleCode],
'24 hour time -hh:mm:ss' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 108) AS [OutputFormat]
UNION ALL
SELECT '109' AS
[StyleCode],
'Default + milliseconds -mon dd yyyy hh:mm:ss:mmmAM (or PM) ' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 109) AS [OutputFormat]
UNION ALL
SELECT '110' AS [StyleCode],
'USA -mm-dd-yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 110) AS [OutputFormat]
UNION ALL
SELECT '111' AS [StyleCode],
'JAPAN -yyyy/mm/dd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 111) AS [OutputFormat]
UNION ALL
SELECT '112' AS [StyleCode],
'ISO -yyyymmdd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 112) AS [OutputFormat]
UNION ALL
SELECT '113' AS [StyleCode],
'Europe default + milliseconds -dd mon yyyy hh:mm:ss:mmm' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 113) AS [OutputFormat]
UNION ALL
SELECT '114' AS [StyleCode],
' 24 hour time with milliseconds -hh:mm:ss:mmm(24h)' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 114) AS [OutputFormat]
UNION ALL
SELECT '120' AS [StyleCode],
'ODBC canonical- yyyy-mm-dd hh:mm:ss(24h)' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 120) AS [OutputFormat]
UNION ALL
SELECT '121' AS [StyleCode],
'ODBC canonical (with milliseconds) -yyyy-mm-dd hh:mm:ss.mmm' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 121) AS [OutputFormat]
UNION ALL
SELECT '126' AS [StyleCode],
'ISO8601 -yyyy-mm-ddThh:mm:ss.mmm' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 126) AS [OutputFormat]
UNION ALL
SELECT '127' AS [StyleCode],
'ISO8601 with time zone Z-yyyy-mm-ddThh:mm:ss.mmmZ' AS
[Standard and Format],
CONVERT(VARCHAR(100), Getdate(), 127) AS [OutputFormat]
UNION ALL
SELECT '131' AS [StyleCode],
'Arabic Hijri date - Islamic calendar' AS [Standard and Format],
CONVERT(VARCHAR(100), Getdate(), 131) AS [OutputFormat]

En la siguiente captura de pantalla, puede ver el código de estilo, sus estándares, formatos y fechas de salida.

Conversión de fechas usando la función FORMAT()

En la función CONVERT() anterior, debemos especificar códigos de estilo para un formato de salida específico. Por lo general, no queremos tener que recordar estos códigos; por lo tanto, Microsoft introdujo la función FORMAT() en SQL Server 2012.

La sintaxis se muestra a continuación.

FORMATO (valor, formato [, cultura])

Valor :Requiere un valor en el formato soportado. Puede consultar la documentación de Microsoft para obtener una lista detallada.

Formato :En el formato, podemos especificar los códigos de formato o patrón para encubrir los datos de fecha de entrada. La siguiente secuencia de comandos muestra los códigos de formato, el patrón y el formato de salida.

DECLARE @InputDate DATETIME = '2020-12-08 15:58:17.643'
SELECT 'd' AS [FormatCode],
'Short Date Pattern' AS 'Pattern',
Format(@InputDate, 'd') AS 'Output'
UNION ALL
SELECT 'D' AS [FormatCode],
'Long Date Pattern' AS 'Pattern',
Format(@InputDate, 'D') AS 'Output'
UNION ALL
SELECT 'f' AS [FormatCode],
'Full Date/Time pattern (Short Time)' AS 'Pattern',
Format(@InputDate, 'f') AS 'Output'
UNION ALL
SELECT 'F' AS [FormatCode],
'Full Date/Time pattern (Long Time)' AS 'Pattern',
Format(@InputDate, 'F')
UNION ALL
SELECT 'g' AS [FormatCode],
'General Date/Time pattern (Short Time)' AS 'Pattern',
Format(@InputDate, 'g')
UNION ALL
SELECT 'G' AS [FormatCode],
'General Date/Time pattern (Long Time)' AS 'Pattern',
Format(@InputDate, 'G') AS 'Output'
UNION ALL
SELECT 'm' AS [FormatCode],
'Month/Day pattern' AS 'Pattern',
Format(@InputDate, 'm') AS 'Output'
UNION ALL
SELECT 'O' AS [FormatCode],
'Round trip Date/Time pattern' AS 'Pattern',
Format(@InputDate, 'O') AS 'Output'
UNION ALL
SELECT 'R' AS [FormatCode],
'RFC1123 pattern' AS 'Pattern',
Format(@InputDate, 'R') AS 'Output'
UNION ALL
SELECT 's' AS [FormatCode],
'Sortable Date/Time pattern' AS 'Pattern',
Format(@InputDate, 's') AS 'Output'
UNION ALL
SELECT 't' AS [FormatCode],
'Short Time pattern' AS 'Pattern',
Format(@InputDate, 't') AS 'Output'
UNION ALL
SELECT 'T' AS [FormatCode],
'Long Time Pattern' AS 'Pattern',
Format(@InputDate, 'T') AS 'Output'
UNION ALL
SELECT 'u' AS [FormatCode],
'Universal sortable Date/Time pattern' AS 'Pattern',
Format(@InputDate, 'u') AS 'Output'
UNION ALL
SELECT 'U' AS [FormatCode],
'Universal Full Date/Time pattern' AS 'Pattern',
Format(@InputDate, 'U') AS 'Output'
UNION ALL
SELECT 'Y' AS [FormatCode],
'Year Month pattern' AS 'Pattern',
Format(@InputDate, 'Y') AS 'Output'

Cultura :Es un argumento opcional y define la cultura. Si no especificamos ninguna cultura, SQL Server usa el idioma de la sesión actual.

En la siguiente consulta, convertiremos un formato de fecha en una referencia cultural específica. Necesitamos especificar el código cultural. Por ejemplo, el código cultural para EE. UU. es en-US y hi-IN es para India.

Los scripts usan la d código de formato para patrones de fechas cortas.

DECLARE @d DATETIME ='2020-12-08 16:36:17.760';
SELECT FORMAT (@d, 'd', 'en-US') AS 'US English',
FORMAT (@d, 'd', 'no') AS 'Norwegian Result',
FORMAT(@d, 'd', 'hi-IN') AS 'India',
FORMAT(@d, 'd', 'ru-RU') AS 'Russian',
FORMAT(@d, 'd', 'gl-ES') AS 'Galician (Spain)',
FORMAT ( @d, 'd', 'en-gb' ) AS 'Great Britain English',
FORMAT (@d, 'd', 'zu') AS 'Zulu',
FORMAT ( @d, 'd', 'de-de' ) AS 'German',
FORMAT ( @d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC)';

Obtiene el formato de fecha en una cultura específica, como se muestra a continuación.

Si desea que la salida de fecha tenga un patrón completo de fecha/hora (tiempo prolongado), especifique el código de formato F y cambiará rápidamente su formato de fecha.

En el formato de fecha, también puede especificar los formatos personalizados y convierte la cadena de fecha de entrada según sus requisitos.

Para especificar las cadenas personalizadas, podemos usar las siguientes abreviaturas.

  • dd:Día del mes (01 a 31)
  • dddd:ortografía del día
  • MM:Número de mes (01 a 12)
  • MMMM:ortografía del mes
  • yy:año en dos dígitos
  • yyyy:año de cuatro dígitos
  • hh:Es la hora 01 a 12
  • HH:Da 24 horas. formato de hora 00 a 23
  • mm:minuto 00 a 59
  • ss:segundo de 00 a 59
  • tt:AM o PM

En el siguiente script, convertimos los formatos de fecha de entrada en múltiples formatos utilizando las abreviaturas o códigos anteriores.

DECLARE @d DATETIME ='2020-12-08 16:36:17.760';
SELECT
FORMAT (@d,'dd/MM/yyyy ') as [Date Format 1] ,
FORMAT (@d, 'dd/MM/yyyy, hh:mm:ss ') as [Date Format 2] ,
FORMAT(@d,'yyyy-MM-dd HH:mm:ss')as [Date Format 3] ,
FORMAT(@d,'Dd MMM yyyy HH:mm:ss')as [Date Format 4] ,
FORMAT(@d,'MMM d yyyy h:mm:ss')as [Date Format 5] ,
FORMAT (@d, 'dddd, MMMM, yyyy')as [Date Format 6] ,
FORMAT (@d, 'MMM dd yyyy') as [Date Format 7] ,
FORMAT (@d, 'MM.dd.yy') as [Date Format 8] ,
FORMAT (@d, 'MM-dd-yy') as [Date Format 9] ,
FORMAT (@d, 'hh:mm:ss tt')as [Date Format 10] ,
FORMAT (@d, 'd-M-yy')as [Date Format 11] ,
FORMAT(@d,'MMMM dd,yyyy')as [Date Format 12]

Uso de AT TIME ZONE en SQL Server 2016 o posterior

Diferentes países siguen diferentes zonas horarias. Por lo general, estas zonas horarias siguen el desplazamiento de la hora universal coordinada (UTC). Algunos ejemplos de zonas horarias son:

  • Hora de verano central de Australia:UTC +10:30
  • Hora estándar de la India:UTC +5:30
  • Hora de verano de la montaña:UTC-6
  • Hora de Singapur:UTC+8
  • Hora de verano central:UTC-5

Puede consultar este artículo para obtener una lista detallada de las zonas horarias.

Muchos países siguen el horario de verano y el reloj se ajusta 1 hora (o 30-45 minutos) dependiendo de las zonas horarias. Por ejemplo, el horario de verano central siguió el siguiente horario:

  • La hora estándar comenzó:1 de noviembre de 2020 a las 02:00 hora local. Los relojes se atrasaron una hora.
  • La hora estándar finaliza el 14 de marzo de 2021 a las 02:00 hora local. Los relojes se adelantarán una hora.

SQL Server no conoce estas zonas horarias ni el horario de verano. Por lo general, una organización sigue las zonas UTC ya que no requiere ningún cambio.

¿Cómo podemos convertir zonas horarias en SQL Server?

Puede usar AT TIME ZONE a partir de SQL Server 2016 y convertir las zonas horarias. En la siguiente consulta, muestra fechas para la hora estándar central, la hora estándar de la India y la hora estándar de Samoa.

Declare @DateinUTC datetime2='2020-11-01 02:00:00'
select
@DateinUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time' as 'Central Standard Time' ,
@DateinUTC AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time' as 'India Standard Time',
@DateinUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Samoa Standard Time' as 'Samoa Standard Time',
@DateinUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Dateline Standard Time' as 'Dateline Standard Time'

Para conocer las zonas horarias admitidas, puede consultar sys.time_zone_info  y devuelve la zona horaria y el desplazamiento.

A continuación, puede filtrar las zonas horarias que actualmente respetan el horario de verano.

Select * from sys.time_zone_info where is_currently_dst=1

Ahora, consideremos el horario de verano para el horario del este.

  • Comenzó el horario de verano:domingo 8 de marzo de 2020 a las 2:00 a. m.
  • Terminó el horario de verano:domingo 1 de noviembre de 2020 a las 2:00 a. m.

Convierta su zona UTC a la hora estándar del este y podrá observar el impacto del horario de verano.

DECLARE
@PreDST datetime = '2020-03-08 06:59:00',
@PostDST datetime = '2020-03-08 07:00:00';
SELECT
@PreDST AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time' AS [EST time before DST],
@PostDST AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time' AS [EST time before DST];

Puntos útiles para usar formatos de fecha SQL CONVERT

Evalúe los requisitos de su aplicación y elija el tipo de datos apropiado fecha, SmallDateTime, DateTime, DateTime2 y DateTimeOffset.

Puede convertir el formato de fecha utilizando las funciones SQL CONVERT date y FORMAT; sin embargo, es recomendable utilizar el formato que mejor se adapte a sus cargas de trabajo. Esto le ayudará a evitar tener que usar la conversión de fecha explícita.

Puede contabilizar el horario de verano en SQL Server utilizando la función AT TIME ZONE a partir de SQL