How to convert TSQL Datetime to Julian INT date - tsql

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;

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

Convert String "Friday June 1, 2018" to Date

I have a column in database from imported file in the format Friday June 1, 2018 and trying to format to a valid date conversion from varchar to date.
I have tried cast and convert with no success
SELECT CAST([Course date] as DATETIME)
FROM [dbo].[Test]
SELECT CONVERT(datetime, [Course date], 103)
FROM [dbo].[Test]
I expected conversion to type 103 UK dd/mm/yyyy
TRY_CONVERT seems to be able to handle your date string. Note that the name of the day is superfluous, and is not needed to determine exactly what the date is. So, we can remove it using base string functions.
WITH yourTable AS (
SELECT 'Friday June 1, 2018' AS datecol
)
SELECT
datecol AS input,
TRY_CONVERT(datetime, STUFF(datecol, 1, CHARINDEX(' ', datecol), '')) AS output
FROM yourTable;
Demo

Change Month and Year in a datetime

I have a datetime field in my query.
Select Account, Period, JEDate
From table
I would like to replace the year of the "JEDate" datetime field with a Parameter "#Year" (int).
I would also like to replace the month with the "Period" (int) field.
Example:
If the JEDate was 1900-01-01 00:00:00.000 (or any other date), the year was 2013 and the month was 2, I would like the JEDate to be 2013-02-01 00:00:00.000.
How do I do this?
Thank you
Perhaps:
UPDATE dbo.TableName
SET JEDate = CONVERT(DATETIME, CAST(#Year as varchar(4)) + '-' + CAST(Period as VARCHAR(2)) + '-' + '01', 102)
WHERE JEDate IS NOT NULL
Demo
An alternative approach that adds the difference between the original year and month, and the new year and month:
select dateadd(year, #year-Year(JEDATE), dateadd(month, Period-Month(JEDATE), JEDATE))

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

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

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)))