sql datetime converted to specific day if between certain times - sql-server

I have a string of datetime records. I'd like to make a case condition or if statement which reads the datetime value and assigns this to a specific day.
The day range is 2:45PM up to the next day at 2:45PM. This range would be considered the 'next day'
Ex. Time of post is 3:42 PM 11/12/2016, therefore this would read as 11/13/2016. If this post was made at 2:42 PM 11/12/2016, then this would have read 11/12/2016.
So far don't believe CONVERT(date, 'datetime') will work due to time range constraints.
Thanks

Use DATEADD function to add time to the date so it gets to the next day. For 2:45PM you'll need to add 9:15.

Think I got it...check if datetime time value is above 2:45, if so, then convert to date and add a day, else convert to date.
CASE
WHEN CAST (MAIN.TimeOfRftDecision AS Time) > '14:45:00' THEN DATEADD(dd,1,CONVERT (Date, MAIN.TimeOfRftDecision))
ELSE CONVERT (Date, MAIN.TimeOfRftDecision)
END AS 'DayOfRft'

Related

Get yesterday start and end datestamp and convert to Unix epoch

I have a Stored Procedure that will run within a time period (between 2-3 am), but not always at the exact same time during that period.
As part of this procedure I need to do 3 steps:
1: Get the start of yesterday's date
So if today is 13/08/2020 13:51:02 I need the query to return 12/08/2020 00:00:00 and do this dynamically
2: Get the end of yesterday's date
In the above this would return 12/08/2020 23:59:59
3: Convert both values into Unix EPOCH timestamps
I have used in the past on a similar issue (that was less time-sensitive) the below bit of Code:
declare #yesterday date
set #yesterday = (SELECT convert(datetime, DATEADD(day, -1 ,getdate()), 23 ))
The Problem here is that this gives a value that is exactly 24 hours in the past, so if the SP is run at 2:15 am - it's time stamp will be different when it's run at 2:23 am or 2:53 am.
Once I've got a method of getting the start and end date to always be correct - I'll then use something like this solution to convert the Datetime into Epoch timestamps, unless someone who answers this question has a snazzy method of doing it all in one (for which I would be eternally grateful)
To get midnight yesterday, do this:
DECLARE #yesterday DATETIME
= DATEADD(DAY, -1, CAST(GETDATE() AS DATE));
To get midnight today do
DECLARE #today DATETIME = CAST(GETDATE() AS DATE);
To filter for times that happened yesterday, do
WHERE ts >= #yesterday AND ts < #today ...
The CAST operation truncates the date/time value returned by GETDATE() to midnight.
The form of WHERE with >= and < copes with the edge case correctly. It also happens to exploit an index on the column I called ts.

How to add an hour in timestamp in sql server (without Declare)

I want to add an hour in the parameter TimeStamp, but not with declare parameter i.e
DECLARE #datetime2 datetime2 = '2019-03-01T09:25:21.1+01:00'
SELECT DATEADD(hour,1,#datetime)
I have a column name TimeStamp in a table and i want to add in all data plus 1 hour.
The column
TimeStamp
2019-03-01T09:25:20.1+01:00
2019-03-01T09:25:21.1+01:00
2019-03-01T09:25:19.1+01:00
I try something like this
SELECT DATEADD(hour,1, TimeStamp), but i have an error
Conversion failed when converting date and/or time from character
string.
Any possible answers ??
Thanks
SELECT DATEADD(hour,1, TimeStamp) is correct
However, The format in TimeStamp is wrong,
So, cast it to DateTime2 First
CAST(TimeStamp as DateTime2)
OR
CAST('2019-03-01T09:25:20.1+01:00' as DateTime2)
So,
SELECT DATEADD(hour, 1, CAST(TimeStamp as DateTime2))
Conversion failed when converting date and/or time from character
string.
The error message means that column TimeStamp stored as a string. DATEADD expects a valid value that is date/datetime/datetime2 or can be converted into it from a string. Because a sample value look like DATETIME2, such extra conversion perhaps is needed:
SELECT DATEADD(hour,1, CAST(TimeStamp as datetime2))
Your syntax will be fine as defined.
It might be a value in your column that is not able to parse to datetime2 because it contains an invalid character.
You could add the ISDATE() to the expression to check if it is valid.
https://learn.microsoft.com/en-us/sql/t-sql/functions/isdate-transact-sql?view=sql-server-2017
edit: forgot to mention you could parse before adding with try_cast or try_convert to datetime2
In Your Timestamp +01:00 represents the Time offset to GMT. You can convert this to your local time and then Add the Hours using DATEADD()
or Remove the Time Offset from the string and add one hour using DATEADD() As suggested by Others.
According to this https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017#date-and-time-styles
you have to convert the timestamp with timezone using type 127.
127 is the input format for:
ISO8601 with time zone Z.
yyyy-mm-ddThh:mi:ss.mmmZ (no spaces)
Note: For a milliseconds (mmm) value of 0, the millisecond decimal value will not display. For example, the value '2012-11-07T18:26:20.000 will display as '2012-11-07T18:26:20'.
select convert(datetime2, '2019-03-01T09:25:20.1+01:00', 127)
if you are not using convert and the 127 by using cast you may run in conversion problems depending on language settings of the users.
Maybe you are after this?
select dateadd(hour,1,convert(datetimeoffset, TimeStamp))
Best to not store dates and times as text though.
Edit: Note that his will retain your time zone information if that is important to you.

Dealing with out of range value on varchar date conversion

I'm attempting to convert dates input in our system as text in the format YYYYMMDD into dates. Unfortunately our system allows the use of the 31st of any month to signify that it's the last day of the month that's important, for some functions like interest accrual etc.
I have a date showing as 20160931 which obviously fails to convert via
CONVERT(DATETIME, CONVERT(CHAR(8), [FIELD]))
and throws the out-of-range value error.
How can I overcome this, so that I can convert it to the correct value, in this case 30/09/2016?
Adapting #Shnugo's technic, I feel it's better to leave SQL to decide the end of month. Hence:
SELECT eomonth(CAST(y+m+'01' AS DATE))
FROM (VALUES(LEFT(#YourDate,4)
,SUBSTRING(#YourDate,5,2)
,SUBSTRING(#YourDate,7,2))) AS Parts(y,m,d)
Will give '2016-02-29' instead of '2016-02-28' with a constant '28' for Feb.
You might try something like this:
DECLARE #YourDate VARCHAR(100)='20160231';
SELECT CAST(y+m+dNew AS DATE)
FROM (VALUES(LEFT(#YourDate,4)
,SUBSTRING(#YourDate,5,2)
,SUBSTRING(#YourDate,7,2))) AS Parts(y,m,d)
CROSS APPLY
(
SELECT CASE WHEN CAST(m AS INT) IN(4,6,9,11) AND CAST(d AS INT)>30 THEN '30'
ELSE CASE WHEN CAST(m AS INT)=2 AND CAST(d AS INT)>28 THEN '28' ELSE d END
END AS dNew
) AS NewDay
And about a 29th of February you just have - additionally - to check if the year is to be divided by 4 :-)
UPDATE
Now it's on me to evolve #Irawan's technique :-)
Since SQL Server 2005 has not got the EOMONTH function, but it is surely better to let SQL Server do the calculation (29th of Feb implicitly solved!), I'd suggest this:
DECLARE #YourDate VARCHAR(100)='20160231';
SELECT DATEADD(SECOND,-1,DATEADD(MONTH,1,CAST(y+m+'01' AS DATETIME)))
FROM (VALUES(LEFT(#YourDate,4)
,SUBSTRING(#YourDate,5,2)
,SUBSTRING(#YourDate,7,2))) AS Parts(y,m,d)
This will - in any case - deliver the last second of the month...
If you want a plain DATE (without a time), you might just change the SECOND to DAY which will first jump to midnight of the first day of the next month and than go one day back...
UPDATE 2 Use existing dates if valid
Simple syntax...
DECLARE #YourDate VARCHAR(100)='20160229';
SELECT CASE WHEN ISDATE(#YourDate)=1 THEN #YourDate
ELSE DATEADD(SECOND,-1,DATEADD(MONTH,1,CAST(LEFT(#YourDate,4) + SUBSTRING(#YourDate,5,2) +'01' AS DATETIME)))
END AS CorrectDate;

Compare dates in MS SQL using Convert

I want to do the correct way to get a date from a #parameter that contains the complete datetime, that user gets from a calendar from TFS File.
In the select I would want to use something like CONVERT(varchar(10), #FechaHasta.Value, 120) AS DATE01 and then get the only date, throwing out the time from the parameter.
For the next step, I would want to compare it with another date in WHERE clause, having this code :
Then, I would want to make this work on for looking for between two dates, and the last one, throwing out the time from the datetime.
Thanks.
I am assuming #FetchHasta is a datetime
CONVERT(VARCHAR(10), #FetchHasta, 101)
is what gets you just the date part. i.e. 10/28/2014 1:10 PM would simply become 10/28/2014.
Source
EDIT: Alternatively, How to return the date part only from a SQL Server datetime datatype

converting start date to datetime as beginning of the day and end date to end of the day

Store PROCEDURE
--para--
#StartingDate DateTime = NULL,
#EndingDate DateTime = NULL
--condition --
dbo.callentry.CallDateTime BETWEEN ISNULL(#StartingDate,
dbo.callentry.CallDateTime) and ISNULL(#EndingDate,dbo.callentry.CallDateTime)
Question :
when i pass date '2012-09-17' from date picker as para #StartingDate, and the same as ending date . it is comparing 2012-09-17 00:00:00.000 to 2012-09-17 00:00:00.000 - will return no records
what i want is records in whole day 2012-09-17
Why not just use #StartingDate-1 then?
Or even DATEADD(d,-1,#StartingDate)
Or #EndDate + 1
Or even DATEADD(d,1,#EndDate)
DATEADD (Transact-SQL)
Returns a specified date with the specified number interval (signed
integer) added to a specified datepart of that date.
Try this:
dbo.callentry.CallDateTime >=ISNULL(#StartingDate,
dbo.callentry.CallDateTime) and dbo.callentry.CallDateTime <=ISNULL(#EndingDate,dbo.callentry.CallDateTime)
Also make sure dbo.callentry.CallDateTime this column datatype is also datetime
OR
Also reading from your question. I think when strt and end date are same you just need all the records for that day. if start and end date are same why cant you just use like below:
convert(date,dbo.callentry.CallDateTime) =convert(date,ISNULL(#StartingDate,
dbo.callentry.CallDateTime))
In case of sql server 2008 if below just convert both the sides to just date format annd compare

Resources