How do you calculate the number of weeks between two dates? - tsql

How do you calculate the number of weeks between two dates?
for example as follows
Declare #StartDate as DateTime = "01 Jan 2009";
Declare #EndDate as DateTime = "01 June 2009";
#StartDate and #EndDate

Use the Datediff function. datediff(ww,#startdate,#enddate)
the ww tells the function what units you require the difference to be counted in.
http://msdn.microsoft.com/en-us/library/ms189794.aspx

You may use the following function to retrives week's between two dates:
CREATE FUNCTION [dbo].[fGetWeeksList]
(
#StartDate DATETIME
,#EndDate DATETIME
)
RETURNS
TABLE
AS
RETURN
(
SELECT DATEADD(DAY,-(DATEPART(DW,DATEADD(WEEK, x.number, #StartDate))-2),DATEADD(WEEK, x.number, #StartDate)) as [StartDate]
,DATEADD(DAY,-(DATEPART(DW,DATEADD(WEEK, x.number + 1, #StartDate))-1) ,DATEADD(WEEK, x.number + 1, #StartDate)) AS [EndDate]
FROM master.dbo.spt_values x
WHERE x.type = 'P' AND x.number <= DATEDIFF(WEEK, #StartDate, DATEADD(WEEK,0,CAST(#EndDate AS DATE)))

Related

Convert Excel formula (using Date and subtraction) into T-SQL

I am trying to write this Excel formula into T-SQL (to write a function).
Expected output is 0.71944444, but currently my output (using T-SQL) is 24.0000.
I am not sure why we have to add a day to same date and subtract the same date.
Bottom is a screenshot from Excel:
This is what I have so far in T-SQL:
CREATE FUNCTION [dbo].[fn_0921] (
#Punch_Start nvarchar(max)
)
RETURNS decimal(36, 8) AS
BEGIN
DECLARE #return_value nvarchar(max);
SET #return_value =
DATEDIFF(
MINUTE, CAST(#Punch_Start AS datetime2),
(
dateadd(
day, 1, CAST(#Punch_Start AS datetime2)
)
)
)
/ (60.0)
RETURN #return_value
END;
Thanks for help.
The Excel formula is returning the difference between the datetime in cell K4 & the start of the next day (i.e. 7/26/2021 00:00) as a fraction of a whole day. The following is the equivalent in T-SQL:
DECLARE #Punch_Start datetime2 = '7/25/2021 06:44';
SELECT DATEDIFF(
MINUTE,
#Punch_Start,
CAST(
CAST(
DATEADD(DAY, 1, #Punch_Start)
AS date) -- Add 1 day to #Punch_Start & cast as date to remove the time component - this is the start of the next day
AS datetime2) -- Cast back to datetime2 to get the difference in minutes
) / 1440.; -- Divide the difference in minutes by the number of minutes in a day (60 minutes per hour, 24 hours per day) to get the difference as a fraction of a day
This can probably help you:
DECLARE #date DATETIME2 = '2021-07-25 06:44'
DECLARE #seconds INT = DATEDIFF(second, CAST(#date AS date), #date)
DECLARE #secondsFromEnd FLOAT = 86400 - #seconds
SELECT #secondsFromEnd / 86400

Find Number Of days and Months and years between 2 Dates

I am trying to Get Years, months and no. of days between 2 dates.
But when dates are like below, it gives wrong output (Month part of FromDate is greater than Todate).
declare #FromDate date='2010-10-27'
declare #Todate date='2012-03-02'
SELECT
DATEDIFF( mm, #FromDate, #ToDate) / 12 AS years
, datediff(mm,#FromDate, #ToDate) % 12 AS months
, DATEDIFF( dd, DATEADD( mm, DATEDIFF( mm, #FromDate, #ToDate), #FromDate), #ToDate) as Days
**It Shows Output as**
Years Months days
1 5 -25
It should be 4 months and 29 days. Please tell me how can I get desired Output.
Thanks in Advance
The following might solve the problem - but I think, the correct values would be 1 year, 4 month and 4 days!?
declare #start date = '2010-10-27'
declare #ende date = '2012-03-02'
SELECT DATEDIFF(mm, #start, #ende)/12 MyYears
,(DATEDIFF(mm, #start, #ende)%12)-1 MyMonths
,DATEDIFF(dd, DATEADD(mm, (DATEDIFF(mm, #start, #ende)%12)-1,DATEADD(yy, DATEDIFF(mm, #start, #ende)/12, #Start)), #Ende) MyDays
--Check of result
SELECT dateadd(dd, 4, dateadd(mm, 4, dateadd(yy, 1, #start))) x
I used this. This gives the desired result.
(#FromDate date,
#ToDate Date
)
DECLARE #Years INT, #Months INT, #Days INT
SET #Years = DATEDIFF(YEAR, #FromDate, #ToDate)
IF DATEADD(YY, #Years, #FromDate) > #ToDate
BEGIN
SET #Years = #Years - 1
END
SET #FromDate = DATEADD(YY, #Years, #FromDate)
SET #Months = DATEDIFF(MM, #FromDate, #ToDate)
IF DATEADD(MM, #Months, #FromDate) > #ToDate
BEGIN
SET #Months = #Months - 1
END
SET #FromDate = DATEADD(MM, #Months, #FromDate)
SET #Days = DATEDIFF(DD, #FromDate, #ToDate)
Select #Years as Years,#Months as Months,
#Days as Days
Maybe this is Correct
declare #FromDate date='2010-10-27'
declare #Todate date='2012-03-02'
SELECT
DATEDIFF( yy,#FromDate,#Todate) AS YEARS,
DATEDIFF( mm,#FromDate,#Todate) AS MONTHS,
DATEDIFF( dd,#FromDate,#Todate) AS DAYS

How can i select all dates between date range?

I have one SQL Table with 2 columns as below
Column1: ProductionDate - DateTime - Not NULL
Column2: Quantity - Int - Not NULL
Now There are 2 Records in Table
1-1-2012, 5
1-3-2012, 7
Output of Result should be as below if i give date range StartDate as 1-1-2012 and EndDate as 1-15-2012
1-1-2012 5
1-2-2012 0
1-3-2012 7
1-4-2012 0
1-5-2012 0
1-6-2012 0
.
.
.
1-15-2012 0
Means Query should return all the dates of given range with Quantity and if no entry in Table then 0 for Quantity.
How to Do it? Please suggest with Query
Here's one very optimistic draft on what you can use ( source - here )
declare #startDate datetime;
declare #endDate datetime;
set #startDate = '2012-02-09';
set #endDate = '2012-02-15';
WITH span AS (
SELECT #startDate AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM span s
WHERE DATEADD(dd, 1, dt) <= #endDate)
select s.dt, t.Quantity from span s
join table t
on s.dt = t.ProductionDate

How to convert TSQL Datetime to Julian INT date

I would like know how to convert date in sql to julian date int,
eg.
if my date was "01 Mar 2011" how do I convert this to Julian date (734197)?
declare #d datetime = '20110301'
select datediff(d, 0, #d) + 693596
DECLARE #normal_date VARCHAR(30)='2024/3/30';
SELECT #normal_date AS NormalDate,CONVERT(varchar,(CONVERT(INT,
SUBSTRING(#normal_date,1,2))%20)+1)+ CONVERT(varchar,
SUBSTRING(CONVERT(varchar,( datepart(year, #normal_date) * 1000 +
datepart(dy, #normal_date))), 3, 5)) AS JulianDate;

TSQL need to return last day of month only, how do I drop year, month & time?

I am writing a function in T-SQL returning the last day of the month regardless of the date input.
Here is my code:
Alter Function dbo.FN_Get_Last_Day_in_Month2
(#FN_InputDt Datetime)
Returns smalldatetime
as
Begin
Declare #Result smalldatetime
Set #Result =
case when #FN_InputDt <> 01-01-1900 then
DATEADD(m, DATEDIFF(M, 0,#FN_InputDt)+1, -1)
Else 0 End
Return #Result
End
The code is not working correctly, here is a test that shows the bad behavior:
SELECT dbo.fn_get_last_day_in_month (07-05-2010)
Here is the (incorrect) result:
2010-07-31 00:00:00
What is 07-05-2010...May 7th or July 5th? You need to use a safe date format, take a look at Setting a standard DateFormat for SQL Server
example from How to find the first and last days in years, months etc
DECLARE #d DATETIME
SET #d = '20100705' -- notice ISO format
SELECT
DATEADD(yy, DATEDIFF(yy, 0, #d), 0) AS FirstDayOfYear,
DATEADD(yy, DATEDIFF(yy, 0, #d)+1, -1) AS LastDayOfYear,
DATEADD(qq, DATEDIFF(qq, 0, #d), 0) AS FirstDayOfQuarter,
DATEADD(qq, DATEDIFF(qq, 0, #d)+1, -1) AS LastDayOfQuarter,
DATEADD(mm, DATEDIFF(mm, 0, #d), 0) AS FirstDayOfMonth,
DATEADD(mm, DATEDIFF(mm, 0, #d)+1, -1) AS LastDayOfMonth,
#d - DATEDIFF(dd, ##DATEFIRST - 1, #d) % 7 AS FirstDayOfWeek,
#d - DATEDIFF(dd, ##DATEFIRST - 1, #d) % 7 + 6 AS LastDayOfWeek
for just the day use day or datepart
select DAY(getdate()),
DATEPART(dd,GETDATE())
Cast the return value to a SQL datetime type, and then call the "DAY" function to get the day in as an integer. See the function reference here:
http://msdn.microsoft.com/en-us/library/ms176052.aspx
Not sure which database you're using, but this should be a standard function across all databases.
I'd return a DATETIME, I've had trouble with SMALLDATETIME in the past.
DECLARE #Result DATETIME
SET #Result = DATEADD(m , 1, #FN_Input);
RETURN CAST(FLOOR(CAST(DATEADD(d, DATEPART(d, #Result) * -1, #Result) AS FLOAT)) AS DATETIME)
Also, I think you may be a victim of SQL's complete disregard of date formatting. Always, always, always, when typing a string into test a SQL function use the following format;
'05 Jul 2010'
Your function probably works but it interpreted your date as 5th July - not 7th May.
DECLARE #date DATETIME = '20130624';
SELECT Day(EOMONTH ( #date )) AS LastDay;
GO