¿Cómo obtener la primera y última fecha del año en curso?


Usando SQL Server 2000, ¿cómo puedo obtener la primera y la última fecha del año en curso?

Producto esperado:

01/01/2012 y 31/12/2012

Author: TylerH, 2012-11-18

15 answers

SELECT
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS EndOfYear

La consulta anterior da un valor datetime para medianoche a principios del 31 de diciembre. Esto es aproximadamente 24 horas antes del último momento del año. Si desea incluir el tiempo que podría ocurrir el 31 de diciembre, entonces debe comparar con el primero del próximo año, con una comparación <. O puede comparar con los últimos milisegundos del año actual, pero esto todavía deja un hueco si está utilizando algo que no sea DATETIME (como DATETIME2):

SELECT
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS LastDayOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0) AS FirstOfNextYear,
   DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)) AS LastTimeOfYear

Tech Detalles

Esto funciona calculando el número de años desde 1900 con DATEDIFF(yy, 0, GETDATE()) y luego sumándolo a una fecha de cero = 1 de enero de 1900. Esto se puede cambiar para trabajar para una fecha arbitraria reemplazando la porción GETDATE() o un año arbitrario reemplazando la función DATEDIFF(...) con "Year - 1900."

 SELECT
   DATEADD(yy, DATEDIFF(yy, 0, '20150301'), 0) AS StartOfYearForMarch2015,
   DATEADD(yy, 2015 - 1900, 0) AS StartOfYearFor2015
 193
Author: Jamie F,
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-11-07 15:48:06

Puede obtener el año actual usando la función DATEPART, a partir de la fecha actual obtenida usando getUTCDate()

SELECT 
    '01/01/' + CONVERT(VARCHAR(4), DATEPART(yy, getUTCDate())), 
    '31/12/' + CONVERT(VARCHAR(4), DATEPART(yy, getUTCDate()))
 8
Author: Vikdor,
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-11-18 04:15:45

Simplemente escriba: -

select convert (date,DATEADD(YEAR,DATEDIFF(YEAR,0,GETDATE()),0))

Fecha de Inicio del año.

select convert (date,DATEADD(YEAR, DATEDIFF(YEAR,0,GETDATE()) + 1, -1))  
 6
Author: Pradeep atkari,
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-11-11 10:19:25

Cada año tiene el 1 er como Primera fecha y el 31 como última fecha lo que tienes que hacer es solo adjuntar el año a ese día y mes por ejemplo: -

 SELECT '01/01/'+cast(year(getdate()) as varchar(4)) as [First Day],
 '12/31/'+cast(year(getdate()) as varchar(4)) as [Last Day]
 4
Author: Rahul Tripathi,
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-11-18 09:22:32

Para la fecha de inicio del año en curso:

SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())

Para la fecha final del año en curso:

SELECT DATEADD(DD,-1,DATEADD(YY,DATEDIFF(YY,0,GETDATE())+1,0))
 1
Author: DHANA LAKSHMI,
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-02-13 14:50:43

Para obtener el primer y el último día del año, se puede usar la función CONCAT. El valor resultante puede ser fundido a cualquier tipo.

CONCAT(YEAR(Getdate()),'-01-01') FirstOfYear,
CONCAT(YEAR(GETDATE()),'-12-31') LastOfYear
 1
Author: Gayle,
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-05-11 14:17:20

Echa un vistazo a este:

select convert(varchar(12),(DateAdd(month,(Month(getdate())-1) * -1, DateAdd(Day,(Day(getdate())-1) * -1,getdate()))),103) as StartYear,
       convert(varchar(12),DateAdd(month,12 - Month(getdate()), DateAdd(Day,(31 - Day(getdate())),getdate())),103) as EndYear
 0
Author: NeverHopeless,
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-11-18 09:03:31
select to_date(substr(sysdate,1, 4) || '01/01'), to_date(substr(sysdate,1, 4) || '12/31') 
from dual
 0
Author: R-Dubz,
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-25 20:45:44
SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())
 0
Author: DHANA LAKSHMI,
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-02-13 13:43:17
print Cast('1/1/' + cast(datepart(yyyy, getdate()) as nvarchar(4)) as date)
 0
Author: zadeveloper,
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-06-01 20:13:06

Parece que usted es interesante en la realización de una operación todo para un año dado, si este es el caso, yo recomendaría utilizar la YEAR () función de esta manera:

SELECT * FROM `table` WHERE YEAR(date_column) = '2012';

Lo mismo ocurre con DÍA() y MES(). También están disponibles para las variantes de MySQL/MariaDB y se introdujeron en SQL Server 2008 (así que no para 2000 específico).

 0
Author: chjortlund,
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-04-11 12:38:42

En Microsoft SQL Server (T-SQL) esto se puede hacer de la siguiente manera

--beginning of year
select '01/01/' + LTRIM(STR(YEAR(CURRENT_TIMESTAMP)))

--end of year
select '12/31/' + LTRIM(STR(YEAR(CURRENT_TIMESTAMP)))

CURRENT_TIMESTAMP - devuelve la fecha de sql server en el momento de la ejecución de la consulta.

YEAR - obtiene la parte del año de la marca de tiempo actual.

STR , LTRIM - estas dos funciones se aplican para que podamos convertir esto en un varchar que se puede concatinar con nuestro prefijo deseado (en este caso es la primera fecha del año o la última fecha de la año). Por cualquier razón, el resultado generado por la función YEAR tiene espacios de prefijo. Para solucionarlos utilizamos la función LTRIM que es trim izquierdo.

 0
Author: Soundararajan,
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-04-29 11:22:01

Otra manera: (Desde SQL Server 2012)

SELECT
    DATEFROMPARTS(YEAR(GETDATE()), 1, 1) FirstDay,
    DATEFROMPARTS(YEAR(GETDATE()),12,31) LastDay
 0
Author: EstevaoLuis,
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-06-12 09:38:08

Prueba esto:

DATE_FORMAT(NOW(),'01/01/%Y')
DATE_FORMAT(NOW(),'31/12/%Y')
 -1
Author: Ivan,
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-02-13 13:51:10

- - - Demos de Lalmuni - - -

create table Users
(
userid int,date_of_birth date
)

---insertar valores---

insert into Users values(4,'9/10/1991')

select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years, 
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months, 
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users
 -3
Author: Lalmuni Singh,
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-03-19 12:07:13