Redondeo de SQL DateTime a medianoche
Tengo un pequeño problema con mi consulta SQL. Estoy usando la función GETDATE, sin embargo, digamos que ejecutoel script a las 5PM, que extraerá registros entre 12/12/2011 5PM a 12/18/2011 5PM. ¿Cómo puedo hacer que tire de los registros de todo el 12/12/2011-12/18/2011 básicamente ignorar el tiempo.
Mi guión:
WHERE Orders.OrderStatus = 'Shipped'
AND Orders.ShipDate > (GETDATE()-6)
8 answers
En SQL Server 2008 y versiones posteriores puede convertir DateTime
a Date
, lo que elimina el elemento time.
WHERE Orders.OrderStatus = 'Shipped'
AND Orders.ShipDate >= (cast(GETDATE()-6 as date))
En SQL Server 2005 y siguientes puede usar:
WHERE Orders.OrderStatus = 'Shipped'
AND Orders.ShipDate >= DateAdd(Day, Datediff(Day,0, GetDate() -6), 0)
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
2016-11-07 20:08:46
Aquí está la cosa más simple que he encontrado
-- Midnight floor of current date
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()))
El DATEDIFF devuelve el número entero de días anteriores o posteriores a 1900-1-1, y el Convertir Datetime lo devuelve a esa fecha a medianoche.
Dado que DateDiff devuelve un entero, puede usar sumar o restar días para obtener el desplazamiento correcto.
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()) + @dayOffset)
Esto no es redondear esto es truncar...Pero creo que eso es lo que se pide. (Para redondear añadir uno y truncar...y eso no es redondear tampoco, que el techo, pero de nuevo lo más probable es lo que quieres. Para agregar realmente redondo .5 (funciona?) y truncar.
Resulta que puedes agregar .5 para GetDate () y funciona como se espera.
-- Round Current time to midnight today or midnight tomorrow
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE() + .5))
Hice todas mis pruebas en SQL Server 2008, pero creo que estas funciones se aplican a 2005 también.
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
2012-06-20 23:10:28
--
-- SQL DATEDIFF getting midnight time parts
--
SELECT GETDATE() AS Now,
Convert(DateTime, DATEDIFF(DAY, 0, GETDATE())) AS MidnightToday,
Convert(DateTime, DATEDIFF(DAY, -1, GETDATE())) AS MidnightNextDay,
Convert(DateTime, DATEDIFF(DAY, 1, GETDATE())) AS MidnightYesterDay
go
Now MidnightToday MidnightNextDay MidnightYesterDay
-------------------- --------------------- --------------------- ---------------------
8/27/2014 4:30:22 PM 8/27/2014 12:00:00 AM 8/28/2014 12:00:00 AM 8/26/2014 12:00:00 AM
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-08-27 23:33:13
SELECT getdate()
Resultado: 2012-12-14 16:03:33.360
SELECT convert(datetime,convert(bigint, getdate()))
Resultado 2012-12-15 00:00:00.000
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
2012-12-18 02:13:30
Como @BassamMehanni mencionó, puede convertir como FECHA en SQL Server 2008 en adelante...
SELECT
*
FROM
yourTable
WHERE
dateField >= CAST(GetDate() - 6 AS DATE)
AND dateField < CAST(GetDate() + 1 AS DATE)
La segunda condición en realidad puede ser solo GetDate()
, pero estoy mostrando este formato como un ejemplo de Less Than DateX
para evitar tener que convertir el campo de datos a una FECHA también, mejorando así el rendimiento de forma masiva.
Si estás en 2005 o menos, puedes usar esto...
SELECT
*
FROM
yourTable
WHERE
dateField >= DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()) - 6, 0)
AND dateField < DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()) + 1, 0)
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
2011-12-18 22:35:21
Intenta usar esto.
WHERE Orders.OrderStatus = 'Shipped'
AND Orders.ShipDate >= CONVERT(DATE, GETDATE())
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-05-07 09:39:08
Esto puede parecer barato, pero está funcionando para mí
SELECCIONE CONVERT (DATETIME, LEFT (CONVERT (VARCHAR, @ dateFieldOrVariable,101),10)+' 00:00:00.000')
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
2017-01-18 16:41:15
Normalmente lo hago
SELECT *
FROM MyTable
WHERE CONVERT(VARCHAR, MyTable.dateField, 101) = CONVERT(VARCHAR, GETDATE(), 101)
Si está utilizando SQL SERVER 2008, puede hacer
SELECT *
FROM MyTable
WHERE CAST(MyTable.dateField AS DATE) = CAST(GETDATE() AS DATE)
Espero que esto ayude
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
2011-12-18 22:28:28