Convert day number to full date in SQL Server - sql

I searched a lot online and could not find it. I found just the opposite - date to day
For example: Day 221 ==> 09/08/2017
This query do from this date to day number:
SELECT DATEPART(DAYOFYEAR, SYSDATETIME())
or
SELECT DATEDIFF(day, CAST(DATEPART(YEAR, GETDATE()) AS CHAR(4)) + '-01-01', GETDATE() + 1) AS number_of_today
Thanks

Yet another option is with DateFromParts() and GetDate() for the current year
Example
Select DateAdd(DAY,221,DateFromParts(Year(GetDate())-1,12,31))
Returns
2017-08-09

This will give you the date as it relates to January 1st, 1900:
SELECT
dateadd(day, dayToConvert, 0)
FROM
myTable
I think you can change it to base off of January 1st, 2017 by:
SELECT
dateadd(day, dayToConvert, '2016-12-31')
FROM
myTable
It is December 31st because you want to add that many days to the date in the third argument.

The DATEADD function should work, as so:
SELECT DATEADD(day,221,someDate) AS someDate2 FROM sometable
Docs here
Tutorial here

Stored Procedure Option:
CREATE PROCEDURE PROC_NUM_TO_DATE #NUM INT,#DATESTART DATE AS
BEGIN
SELECT DATEADD(DAY,#NUM ,DATEADD(Day,-1,#DATESTART))
END
GO
EXECUTE:
EXEC PROC_NUM_TO_DATE 221,'2017-01-01'
RESULT:
2017-08-09

Related

nth day to nth month in SQL Server

I need to get date between two date range. That is nth day of nth month.
For example, I need to know 23rd day of every 2nd month between January 1, 2015 to December 30, 2015.
I need the query in T-SQL for SQL Server
You should use recursive query in MSSQL.
Here the first WITH DT is a table where you set up conditions:
WITH DT AS
(
SELECT CAST('January 1, 2015' as datetime) as dStart,
CAST('December 30, 2015' as datetime) as dFinish,
31 as nDay,
2 as nMonth
),
T AS
(
SELECT DATEADD(DAY,nDay-1,
DATEADD(MONTH, DATEDIFF(MONTH, 0, DStart), 0)
) as d,0 as MonthNumber
FROM DT
UNION ALL
SELECT DATEADD(DAY,nDay-1,
DATEADD(MONTH, DATEDIFF(MONTH, 0, DStart)
+T.MonthNumber+nMonth,0)
)as d, T.MonthNumber+nMonth as MonthNumber
FROM T,DT
WHERE DATEADD(DAY,nDay-1,
DATEADD(MONTH, DATEDIFF(MONTH, 0, DStart)
+T.MonthNumber+nMonth,0)
)<=DT.dFinish
)
SELECT d FROM T,DT WHERE DAY(d)=DT.nDay
SQLFiddle demo
Is this what you are trying to achieve?
DECLARE #startDate datetime
DECLARE #endDate datetime
DECLARE #monthToFind INT
DECLARE #dayToFind INT
SET #startDate = '01/01/2015'
SET #endDate = '12/31/2015'
SET #monthToFind = 2
SET #dayToFind = 20
IF MONTH(#startDate) + (#monthToFind - 1) BETWEEN MONTH(#startDate) AND MONTH(#endDate)
AND YEAR(#startDate) = YEAR(#endDate)
BEGIN
DECLARE #setTheDate datetime
SET #setTheDate = CAST(MONTH(#startDate) + (#monthToFind - 1) AS varchar) + '/' + CAST(#dayToFind AS varchar) + '/' + CAST(YEAR(#startDate) AS varchar)
SELECT DATENAME(DW,#setTheDate)
END
This is clearly homework, and the point of homework is to learn how things work and to solve problems, not to get others to do it for you. So - pointers for doing this properly, rather than an answer to copy and paste.
Numbers / tally tables are ideal for this sort of thing. Create a function that returns a list of sequential integers in a range. More general than a calendar table, and you can use it to derive a calendar table later if you need one.
When you've got that, DATEDIFF will give you the number of days between two dates. Use that to work out the size of your range, DATEADD to increment your date and possibly DATEPART to check that a date is the nth day of the month.
Mess about with those bits for a little while and you'll work it out.

SQL query to find employee aniversary

I need to find anniversary date and anniversary year of employees and send email in every 14 days.But I have a problem with last week of December when using the following query if start date and end date are in different years.
Select * from Resource
where (DATEPART(dayofyear,JoinDate)
BETWEEN DATEPART(dayofyear,GETDATE())
AND DATEPART(dayofyear,DateAdd(DAY,14,GETDATE())))
Instead of comparing to a dayofyear (which resets to zero at jan 1st and is the reason your query breaks within 14 days of the end of the year) you could update the employee's joindate to be the current year for the purpose of the query and just compare to actual dates
Select * from Resource
-- Add the number of years difference between joinDate and the current year
where DATEADD(year,DATEDIFF(Year,joinDate,GetDate()),JoinDate)
-- compare to range "today"
BETWEEN GetDate()
-- to 14 days from today
AND DATEADD(Day,14,GetDate())
-- duplicate for following year
OR DATEADD(year,DATEDIFF(Year,joinDate,GetDate())+1,JoinDate) -- 2016-1-1
BETWEEN GetDate()
AND DATEADD(Day,14,GetDate())
Test query:
declare #joindate DATETIME='2012-1-1'
declare #today DATETIME = '2015-12-26'
SELECT #joinDate
where DATEADD(year,DATEDIFF(Year,#joinDate,#today),#JoinDate) -- 2015-1-1
BETWEEN #today -- 2015-12-26
AND DATEADD(Day,14,#today) -- 2016-01-09
OR DATEADD(year,DATEDIFF(Year,#joinDate,#today)+1,#JoinDate) -- 2016-1-1
BETWEEN #today -- 2015-12-26
AND DATEADD(Day,14,#today) -- 2016-01-09
(H/T #Damien_The_Unbeliever for a simple fix)
The above correctly selects the joinDate which is in the first week of Jan (note I've had to fudge #today as Ive not managed to invent time travel).
The above solution should also solve the issue with leap years that was hiding in your original solution.
Update
You expressed in comments the requirement to select AnniversaryDate and Years of service, you need to apply some CASE logic to determine whether to add 1 (year or date) to your select
select *,
CASE
WHEN DATEADD(YEAR,DATEDIFF(Year,JoinDate,GETDATE()),JoinDate) < GetDate()
THEN DATEDIFF(Year,JoinDate,GETDATE())+1
ELSE DATEDIFF(Year,JoinDate,GETDATE())
END as [Years],
CASE WHEN DATEADD(YEAR,DATEDIFF(Year,JoinDate,GETDATE()),JoinDate) < GetDate()
THEN DATEADD(YEAR,DATEDIFF(Year,JoinDate,GETDATE())+1,JoinDate)
ELSE DATEADD(YEAR,DATEDIFF(Year,JoinDate,GETDATE()),JoinDate)
end as [AnniversaryDate]
.... // etc
You could do this:
Select * from Resource
where DATEPART(dayofyear,JoinDate)
BETWEEN DATEPART(dayofyear,GETDATE())
AND DATEPART(dayofyear,DateAdd(DAY,14,GETDATE()))
OR
DATEPART(dayofyear,JoinDate)
BETWEEN (DATEPART(dayofyear,GETDATE()) + 365)
AND (DATEPART(dayofyear,DateAdd(DAY,14,GETDATE())) + 365)
Try this:
DECLARE #Today DATE = GETDATE() --'12/25/2013'
DECLARE #Duration INT = 14
;WITH Recur AS
(
SELECT #Today AS RecurDate
UNION ALL
SELECT DATEADD(DAY, 1, RecurDate)
FROM Recur
WHERE DATEDIFF(DAY, #Today, RecurDate)+1 < #Duration
)
SELECT
r.*
FROM
Resource r
JOIN Recur
ON CONVERT(VARCHAR(5), JoinDate, 101) = CONVERT(VARCHAR(5), RecurDate, 101)
WHERE JoinDate < #Today
You can use the SQL DATEADD() function with week number parameter
Here is how you can use it:
DECLARE #date date = getdate()
Select * from Resource
where
JoinDate BETWEEN #date AND DATEADD(ww,2,#date)

Specific day of current month and year

I have problem with return of specific day of current month and year. I need for example 15th day. Until now I used in FB/IB existing function:
IB_EncodeDate(EXTRACT(YEAR FROM Current_Date),EXTRACT(Month FROM Current_Date),15)
Does it exist a simply way to convert this for MSSQL database?
edit. I need output in OLE format (41,348 by example) to compare date with another date. I compare date from database with 15th day of current month.
For the 15th day of current month:
SELECT DATEADD(DAY, 14, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0));
To get the silly OLE representation based on this "magic" date, 1899-12-30:
SELECT DATEDIFF(DAY, -2, DATEADD(DAY, 14,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)));
Answer (on March 11th, when I updated this answer for the changed requirement):
-----
41348
So, you have a date, and want to return the 15th day of the same month?. Well, assuming SQL Server 2008, you could do this:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'15',112)
For Previous versions of SQL Server:
SELECT CONVERT(DATETIME,CONVERT(VARCHAR(6),GETDATE(),112)+'15',112)
This seems like a quick answer.
declare #OLEDate int
declare #currentDate as datetime
set #currentDate = DATEADD(DAY, 14, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
set #OLEDate = convert(float, #currentdate)
-- PRINT #OLEDate
based on Aaron Bertrand's answer and your need for the integer conversion
To get 10th day of current day
declare #cur_month int,#cur_yr int,#tenth_dt date
set #cur_month=month(getdate())
set #cur_yr=YEAR(getdate())
set #tenth_dt=convert(date,'10/'+convert(varchar(5),#cur_month)+'/'+convert(varchar(5),#cur_yr),103)
select #tenth_dt
Not sure if you after Day or Date. This gives both dayOfWeek and specificDate for any culture
declare #myDay int = 15
select convert(date,myday) specificDate, datename(dw,myday) dayOfWeek
from (
select convert(varchar(6),getdate(),112) + convert(varchar, #myDay) myday
) x
Fiddle Demo Here
| SPECIFICDATE | DAYOFWEEK |
----------------------------
| 2013-02-15 | Friday |
Current_Date in SQL Server would be getdate().
To get the 15th day in OLE Automation format, try:
select datediff(day, '18991230', dateadd(day, -day(getdate()) + 15, getdate()))
A bit more straightforward approach:
CAST(FORMAT(GETDATE(), 'yyyy-MM-15') AS DateTime)

(sql server 2005) How to determine the WEEK number starting from GETDATE() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting week number off a date in MS SQL Server 2005?
Please suppose (i am in Italy) that all the weeks start with Monday and end with Sunday.
I would like to write a scalar valued function that determines the number of the week with reference to GETDATE()
Thank you in advance for your kind cooperation.
PLEASE PAY ATTENTION TO THIS: The SELECT has to be INDIPENDENT from the SET DATEFIRST command!!
Can you use the two liner?
SET DATEFIRST 1;
SELECT DATEPART( WEEK , GETDATE())
for today
SELECT DATEPART( WEEK , GETDATE())
returns 30 whereas
SET DATEFIRST 1;
SELECT DATEPART( WEEK , GETDATE())
returns 31
Edit Untested but based on This Question you can get the equivalent of the SQL Server 2008 datepart(iso_week, getdate()) (which i believe is what you want) with the following select statement
SELECT ISOWeek = (DATEPART(DY, Th) - 1) / 7 + 1
FROM (SELECT Th = DATEADD(D, 3 - (DATEPART(DW, getdate()) + ##DATEFIRST - 2) % 7, getdate())) s
Here's a little snippet that should do what you need.
DECLARE #firstOfYear DATETIME
SET #firstOfYear = STR(Year(GETDATE()), 4)+'-01-01 00:00:00'
SELECT DATEDIFF(ww, #firstOfYear - ((DATEPART(dw, #firstOfYear) + 5) % 7), GETDATE())
Keep in mind that if you want to set the week start to on a different day, just change the +5 to the value based on 7 - dw. This is for MSSQL.
This works by getting the first day of the year and finding the day of the starting week on or before that day. Then we get the number of weeks between whatever date was passed in and that "first" week start. If you want to allow any date to be passed in, just replace all GETDATE calls with your parameter and you should be good to go. If you need a single select statement:
SELECT
DATEDIFF(ww, day1 - ((DATEPART(dw, day1) +5) % 7), GETDATE())
FROM
(SELECT CAST(STR(Year(GETDATE()), 4)+'-01-01 00:00:00' AS DATETIME) day1) d
select datepart(week,getdate())
more at http://msdn.microsoft.com/en-us/library/aa258265(v=sql.80).aspx
declare #oldDF int
set #oldDF = ##DATEFIRST
set DATEFIRST 1
select DATEPART(WEEK, GETDATE())
set DATEFIRST #oldDF

Get month and year from a datetime in SQL Server 2005

I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?
select
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)
If you mean you want them back as a string, in that format;
SELECT
CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120)
FROM customers
Here are the other format options
Beginning with SQL Server 2012, you can use:
SELECT FORMAT(#date, 'yyyyMM')
Use:
select datepart(mm,getdate()) --to get month value
select datename(mm,getdate()) --to get name of month
In SQL server 2012, below can be used
select FORMAT(getdate(), 'MMM yyyy')
This gives exact "Jun 2016"
Funny, I was just playing around writing this same query out in SQL Server and then LINQ.
SELECT
DATENAME(mm, article.Created) AS Month,
DATENAME(yyyy, article.Created) AS Year,
COUNT(*) AS Total
FROM Articles AS article
GROUP BY
DATENAME(mm, article.Created),
DATENAME(yyyy, article.Created)
ORDER BY Month, Year DESC
It produces the following ouput (example).
Month | Year | Total
January | 2009 | 2
How about this?
Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )
That format doesn't exist. You need to do a combination of two things,
select convert(varchar(4),getdate(),100) + convert(varchar(4),year(getdate()))
( Month(Created) + ',' + Year(Created) ) AS Date
the best way to do that is with :
dateadd(month,datediff(month,0,*your_date*),0)
it will keep your datetime type
cast(cast(sq.QuotaDate as date) as varchar(7))
gives "2006-04" format
The question is about SQL Server 2005, many of the answers here are for later version SQL Server.
select convert (varchar(7), getdate(),20)
--Typical output 2015-04
SQL Server 2005 does not have date function which was introduced in SQL Server 2008
returns the full month name, -, full year e.g. March-2017
CONCAT(DATENAME(mm, GetDate()), '-', DATEPART(yy, GetDate()))
I had the same problem and after looking around I found this:
SELECT DATENAME(yyyy, date) AS year
FROM Income
GROUP BY DATENAME(yyyy, date)
It's working great!
Converting the date to the first of the month allows you to Group By and Order By a single attribute, and it's faster in my experience.
declare #mytable table(mydate datetime)
declare #date datetime
set #date = '19000101'
while #date < getdate() begin
insert into #mytable values(#date)
set #date = dateadd(day,1,#date)
end
select count(*) total_records from #mytable
select dateadd(month,datediff(month,0,mydate),0) first_of_the_month, count(*) cnt
from #mytable
group by dateadd(month,datediff(month,0,mydate),0)
---Lalmuni Demos---
create table Users
(
userid int,date_of_birth date
)
---insert values---
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
Yes, you can use datename(month,intime) to get the month in text.
,datename(month,(od.SHIP_DATE)) as MONTH_
Answer:
MONTH_
January
January
September
October
December
October
September
It's work great.
DECLARE #pYear VARCHAR(4)
DECLARE #pMonth VARCHAR(2)
DECLARE #pDay VARCHAR(2)
SET #pYear = RIGHT(CONVERT(CHAR(10), GETDATE(), 101), 4)
SET #pMonth = LEFT(CONVERT(CHAR(10), GETDATE(), 101), 2)
SET #pDay = SUBSTRING(CONVERT(CHAR(10), GETDATE(), 101), 4,2)
SELECT #pYear,#pMonth,#pDay
The following works perfectly! I just used it, try it out.
date_format(date,'%Y-%c')