Cómo convertir una fecha y hora a cadena en T-SQL


Me sorprende no poder encontrar esta pregunta aquí ya.

Tengo un var de fecha y hora y quiero convertirlo en una cadena para poder agregarlo a otra cadena. Lo quiero en un formato que se pueda convertir fácilmente a una fecha y hora.

¿Cómo puedo hacer esto?

(Quiero la parte fecha y la parte hora.)

Author: cja, 2013-02-22

8 answers

La siguiente consulta obtendrá la fecha y hora actual y la convertirá en cadena. con el siguiente formato
yyyy-mm-dd hh:mm:ss(24h)

SELECT convert(varchar(25), getdate(), 120) 
 119
Author: John Woo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-22 17:25:38

Hay muchas maneras diferentes de convert a datetime a una cadena. Aquí hay una manera:

SELECT convert(varchar(25), getdate(), 121)  – yyyy-mm-dd hh:mm:ss.mmm

Ver Demo

Aquí hay un sitio web que tiene una lista de todas las conversiones:

Cómo formatear la fecha y hora en SQL Server

 25
Author: Taryn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-22 17:26:04

Puede usar la instrucción convert en Microsoft SQL Server para convertir una fecha en una cadena. Un ejemplo de la sintaxis utilizada sería:

SELECT convert(varchar(20), getdate(), 120)

Lo anterior devolvería la fecha y hora actuales en una cadena con el formato de YYYY-MM-DD HH:MM:SS en reloj de 24 horas.

Puede cambiar el número al final de la instrucción a uno de muchos que cambiará el formato de las cadenas devueltas. Una lista de estos códigos se puede encontrar en el MSDN en la sección de referencia CAST y CONVERT.

 7
Author: Jeremy1026,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-22 17:28:46

Hay 3 métodos diferentes dependiendo de cuál es mi requisito y qué versión estoy usando.

Aquí están los métodos..

1) Usando Convert

DECLARE @DateTime DATETIME = GETDATE();
--Using Convert
SELECT
    CONVERT(NVARCHAR, @DateTime,120) AS 'myDateTime'
    ,CONVERT(NVARCHAR(10), @DateTime, 120) AS 'myDate'
    ,RIGHT(CONVERT(NVARCHAR, @DateTime, 120),8) AS 'myTime'

2) Usando Cast (SQL Server 2008 y más allá)

SELECT
    CAST(@DateTime AS DATETIME2) AS 'myDateTime'
    ,CAST(@DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
    ,CAST(@DateTime AS DATE) AS 'myDate'
    ,CAST(@DateTime AS TIME) AS 'myTime'
    ,CAST(@DateTime AS TIME(3)) AS 'myTimeWithPrecision'

3) Usando el tipo de datos de caracteres de longitud fija

DECLARE @myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, @DateTime, 120);
DECLARE @myDate NVARCHAR(10) = CONVERT(NVARCHAR, @DateTime, 120);

SELECT
    @myDateTime AS 'myDateTime'
    ,@myDate AS 'myDate'
 5
Author: Todd.J.Hayden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-20 01:12:22

Además de las funciones CAST y CONVERT en las respuestas anteriores, si está utilizando SQL Server 2012 y superiores, utilice la función FORMAT para convertir un tipo basado en DATETIME en una cadena.

Para convertir de nuevo, utilice las funciones opuestas PARSE o TRYPARSE.

Los estilos de formato se basan en.NET (similar a las opciones de formato de cadena del método toString ()) y tiene la ventaja de ser consciente de la cultura. eg.

DECLARE @DateTime DATETIME2 = SYSDATETIME();
DECLARE @StringResult1 NVARCHAR(100) = FORMAT(@DateTime, 'g') --without culture
DECLARE @StringResult2 NVARCHAR(100) = FORMAT(@DateTime, 'g', 'en-gb') 
SELECT @DateTime
SELECT @StringResult1, @StringResult2
SELECT PARSE(@StringResult1 AS DATETIME2)
SELECT PARSE(@StringResult2 AS DATETIME2 USING 'en-gb')

Resultados:

2015-06-17 06:20:09.1320951
6/17/2015 6:20 AM
17/06/2015 06:20
2015-06-17 06:20:00.0000000
2015-06-17 06:20:00.0000000
 3
Author: g2server,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-17 13:33:20

Compruebe la sintaxis de CONVERSIÓN y CONVERSIÓN de t-sql:

Http://msdn.microsoft.com/en-us/library/ms187928.aspx

 1
Author: Antonio Papa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-22 17:28:17

Prueba a continuación:

DECLARE @myDateTime DATETIME
SET @myDateTime = '2013-02-02'

-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
 0
Author: Gaurav123,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-22 18:09:14
SELECT CONVERT(varchar, @datetime, 103) --for UK Date format 'DD/MM/YYYY'

101-US-MM/DD / AAAA

108 - Time-HH:MI:SS

112-Date-AAAAMMDD

121-ODBC-AAAA-MM-DD HH: MI: SS.FFF

20-ODBC-AAAA-MM-DD HH:MI:SS

 0
Author: Rajsanthosh Sreenivasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-12 08:56:05