SQL: How to get the date yyyy/mm/dd based on the year and day number? - sql

I have the following string 2015089 or 2016075, for example.
I need to get the result in yyyy/mm/dd format based on the given input.
So, based on 2015089, I get, 2015/mm/dd. dd is a 89th day of 2015 and mm is a month that has 89th day.
How can I do something like that?

I think the simplest way is to convert to a date using dateadd():
select dateadd(day, right(str, 3) - 1, datefromparts(left(str, 4) + 0, 1, 1) )
That is, add one less than the number of days to the beginning of the year. This assumes that Jan 1 is represented as "1" and not "0".
You can then format the date however you like.
In pre-SQL Server 2012, you can do:
select dateadd(day, right(str, 3) - 1, cast(left(str, 4) + '0101' as date))

Related

Convert Julian/Ordinal date to date in SQL Server 2014

I need to convert this string 2020121 as 2020-04-30 in SQL Server?
How do I do that?
I think that your use of Julian date is the number of days (minus 1) since the start of the year. If so, you can use:
select dateadd(day,
convert(int, right(string, 3)) - 1,
datefromparts(convert(int, left(string, 4)), 1, 1)
)
Here is a db<>fiddle.

CONVERT is presenting the wrong year

I'm using SQL Server 2014, and I'm trying to perform a data conversion, the value being passed '04-SEP-44'
Since this was the birth year, it needs to be 1944, not 2044.
I've tried
select convert(DATETIME, '04-SEP-44')
select convert(DATETIME, '04-SEP-44', 1)
select convert(DATETIME, '04-SEP-44', 13)
But they are all using the year as 2044.
Are there any quick fixes to this issue?
Possibilities:
If the value is greater than today subtract 100 years...
Force "19" into the string...
But it really depends on your business rules, is it always going to be 1900, or could some dates be early 2000's? You should really update your front end to capture the full date.
select case when Y.[Value] > getdate() then dateadd(year, -100, Y.[Value]) else Y.[Value] end
, convert(date, substring(X.[Value], 1, 7) + '19' + substring(X.[Value], 8, 2))
from (values ('04-SEP-44')) as X ([Value])
cross apply (values (convert(date, X.[Value]))) as Y ([Value]);
Note: why would you convert a date to a datetime? Don't use a datetime if you don't have a time component.

How to get start and end of month in numeric type for SQL where clause

I want to run a query monthly to look for records from the previous month. The where clause will be greater or equal to the 1st day of the month and less or equal to the last day. The difficultly I am having is the dates are stored as numbers in a column with a numeric data type. The format being used is yyyymmdd. We are currently manually changing the where clause, so e.g. show me any records with dates >=20201001 to <=20201031, but we need to automate this process. I have tried a few ways to try and solve this but need some guidance.
So far I've tried:
select concat( CONCAT(cast((Year(DATEADD(month, -1, getdate()))) as numeric),cast((Month(DATEADD(month, -1, getdate()))) as numeric)),'01')
Returns error message operand data type numeric is invalid for concat operator. Works in separate query window returning format yyyymmdd.
SELECT DATEADD(mm, DATEDIFF(mm, 0, (DATEADD(month, -1, getdate()))), 0)
Returns error message arithmetic overflow error converting expression to data type date time. Works partly in separate query window but returns yyyy-mm-dd hh:mi:ss:ms
Any help would be greatly appreciated.
Thanks
The real solution is fix the design; don't store dates in a datatype other than a date and time data type.
What you can do, however, is convert the value of GETDATE() to a numerical value of the same format:
SELECT ...
FROM ...
WHERE NumericalDate >= CONVERT(varchar(8),DATEADD(DAY, 1, EOMONTH(GETDATE(),-1)),112)
AND NumericalDate < CONVERT(varchar(8),DATEADD(DAY, 1, EOMONTH(GETDATE())),112)
For today, this would return rows where NumericalDate is in November 2020 (specifically on or after 20201101 and before but not on 20201201).
Note, I don't "bother" to CAST/CONVERT the varchar to a Numerical data type, as it'll be implicit cast due to data type precedence.
You can use artihmetics like so:
where dates >= year(getdate()) * 10000 + month(getdate()) * 100 + 1
and dates < year(dateadd(month, 1, getdate())) * 10000 + month(dateadd(month, 1, getdate())) * 100 + 1
Compare the month and forget the days.
BETWEEN 20201000 and 20201099 finds the same rows as your example >=20201001 to <=20201031
That means that you do not have to figure out how many days are in the month.

Find Birthday in upcoming month

I Need help in finding upcoming birthday in a month.
My Data is something like below , Both data types are nvarchar
Could anyone help me with the sql query please? how to set the DOB column into a date format and then find the birthday with month as 11 and date as 24.
Thanks in advance
Assuming SQL Server, you can use month() to extract the month from a date, for example getdate(), which is the current point in time. With left() you can extract the first characters of a string. That leads to something like:
SELECT [Name],
[Dob(mmdd)]
FROM elbat
WHERE month(getdate()) = left([Dob(mmdd)], 2);
In Microsoft SQL Server you can Create a date using the DATEFROMPARTS(int year, int month, int day) function. To get your month and day you would have to get the 2 parts of the string, the first 2 characters for month and the third and fourth characters as the day, you can use the SUBSTRING function for this. Then take each pair of characters for month and day and cast to int and use them in the DATEFROMPARTS function.
Then you want to see if your newly created date is BETWEEN today AND one month from today. So you could do something like this:
SELECT *
FROM SomeTable
WHERE
DATEFROMPARTS(YEAR(GETDATE()), CAST(SUBSTRING([Dob(mmdd)], 1, 2) as INT), CAST(SUBSTRING([Dob(mmdd)], 3, 2) as INT))
BETWEEN
DATEADD(DAY, -1, GETDATE()) AND DATEADD(MONTH, 1, GETDATE())
Note: this assumes [Dob(mmdd)] is always 4 characters.
You don't need the DOB in a date format. I am unclear what "upcoming" month means, but I suspect that it means a calendar month. If the current month, then:
where month(getdate()) = cast(left(dob, 2) as int)
If the next month, then:
where month(dateadd(month, 1, getdate())) = cast(left(dob, 2) as int)
Thanks, Everyone for the help.. I got this working,. both works perfect
select [USER_ID],[EMP_FULL_NM],[Birthday_Date] from [dbo].[COE]
where month(getdate())=left([Birthday_Date],2)
select [USER_ID],[JOINING_DT],[EMP_FULL_NM] from [dbo].[COE]
where SUBSTRING(CONVERT(VARCHAR(10), [JOINING_DT], 101),1,2) = month(getdate())

Format varchar type and convert it to date variable

I have a varchar value in this format “YYYYMM-LL” where: YYYY is four digit year; MM is two digit month.LL is two digit length of reporting period. This is the number of whole months included in the calculations (from first to last day of each month).
My questions is how I could use this varchar value to decide two variables:#First_Date and #Last_Date.
Example: 201409-06
This scenario is for the six months ending in September of 2014.
The range of calendar dates in this scenario is 04/01/2014 through 09/30/2014.
So how could I use t-sql to find this two dates #First_Date : 04/01/2014 and #Last_Date: 09/30/2014.
Any help would be really appreciated!
You can do something like this:
select #firstdate = dateadd(month, 1 - cast(right('201409-06', 2) as int),
convert(date, left('201409-06', 6) + '01')
),
#lastdate = dateadd(day, -1,
dateadd(month, 1,
convert(date, left('201409-06', 6) + '01')
)
)
This parses the string to do the date arithmetic that you want. SQL Server recognizes a string in the form of "YYYYMMDD" as a date, regardless of internationalization settings.
And a SQL Fiddle.