Subtract one day from datetime - sql

I have a query to fetch date diff between 2 datetime as :
SELECT DATEDIFF(DAY, #CreatedDate , GETDATE())
Ex :
SELECT DATEDIFF(DAY, '2013-03-13 00:00:00.000' , GETDATE())
I need to have a query work like this which will subtract a day from created day:
SELECT DATEDIFF(DAY, **#CreatedDate- 1** , GETDATE())

Try this
SELECT DATEDIFF(DAY, DATEADD(day, -1, '2013-03-13 00:00:00.000'), GETDATE())
OR
SELECT DATEDIFF(DAY, DATEADD(day, -1, #CreatedDate), GETDATE())

I am not certain about what precisely you are trying to do, but I think this SQL function will help you:
SELECT DATEADD(day,-1,'2013-04-01 16:25:00.250')
The above will give you 2013-03-31 16:25:00.250.
It takes you back exactly one day and works on any standard date-time or date format.
Try running this command and see if it gives you what you are looking for:
SELECT DATEADD(day,-1,#CreatedDate)

To simply subtract one day from todays date:
Select DATEADD(day,-1,GETDATE())
(original post used -7 and was incorrect)

Apparently you can subtract the number of days you want from a datetime.
SELECT GETDATE() - 1
2016-12-25 15:24:50.403

This should work.
select DATEADD(day, -1, convert(date, GETDATE()))

SELECT DATEDIFF (
DAY,
DATEDIFF(DAY, #CreatedDate, -1),
GETDATE())

Try this, may this will help you
SELECT DATEDIFF(DAY, DATEADD(DAY,-1,'2013-03-13 00:00:00.000') , GETDATE())

To be honest I just use:
select convert(nvarchar(max), GETDATE(), 112)
which gives YYYYMMDD and minus one from it.
Or more correctly
select convert(nvarchar(max), GETDATE(), 112) - 1
for yesterdays date.
Replace Getdate() with your value OrderDate
select convert(nvarchar (max),OrderDate,112)-1 AS SubtractDate FROM Orders
should do it.

You can try this.
Timestamp=2008-11-11 13:23:44.657;
SELECT DATE_SUB(OrderDate,INTERVAL 1 DAY) AS SubtractDate FROM Orders
output :2008-11-10 13:23:44.657
I hope, it will help to solve your problem.

Related

SQL, get any data between two days and specific time

I am trying to get any data that is between that time range of two days ago until yesterday.
Example: Retrieve any data between 3 PM two days ago and yesterday 3 PM. This query should work on the daily basis.
I am thinking something like but just don't know where to insert the time
select * from dbo.table where system_date between getdate()-2 and getdate()-1
You can use CAST(CAST(GETDATE() AS date) AS datetime) to get the beginning of today's date, then use DATEADD to subtract 1 or 2 days, and add 15 hours.
I strongly suggest you use >= AND < on dates, rather than BETWEEN, otherwise you get "on the interval" issues.
SELECT t.*
FROM dbo.[table] t
WHERE t.system_date >= DATEADD(hour, 15, DATEADD(day, -2, CAST(CAST(GETDATE() AS date) AS datetime)))
AND t.system_date < DATEADD(hour, 15, DATEADD(day, -1, CAST(CAST(GETDATE() AS date) AS datetime)));
try this
select *
from dbo.table
where system_date between dateadd(day, datediff(day, 2, getdate()), '15:00:00') and dateadd(day, datediff(day, 1, getdate()), '15:00:00')
You should use DATEADD for subtracting dates. Your query will look like this.
select *
from table
where system_date between dateadd(day, -2, getdate()) and dateadd(day, -1, getdate())

How to get data for the last week data?

I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?
SET DATEFIRST 1
select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE< dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
Thanks.
select * from table_abc WHERE
CAST(CONTRACT_UPDATE_DATE as date) between
CAST(DATEADD(dd, -7, GETDATE()) as date) and
CAST(GETDATE() AS DATE)
use dateadd to get 1 week before current date.
You can remove the cast as date if you need to validate by timestamp also.
You can try this,
SELECT Created_Date
FROM sample1
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
I suggest this solution:
select * from DB where Datediff(day, CONVERT(DATE, Sysdatetime()),
CONVERT(DATE, CONTRACT_UPDATE_DATE))<=7 and Datediff(day, CONVERT(DATE, Sysdatetime()),
CONVERT(DATE, CONTRACT_UPDATE_DATE))>0
You could try to achieve this by using the calender week.
Try the following:
-- Get last calendar week in format JJJJWW
DECLARE #jjjjkw varchar(6)
SELECT #jjjjkw =
CONVERT(varchar, DATEPART(YYYY,GETDATE()-7)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))) = 1 THEN '0'
+ CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7)) END
-- Compare with the calendar week of your data-set
SELECT DISTINCT [...]
WHERE
CONVERT(varchar, DATEPART(YYYY,CONTRACT_UPDATE_DATE)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))) = 1
THEN '0' + CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE)) END = #jjjjkw
Maybe not the most elegant way but it should work.

Getdate() functionality returns partial day in select query

I have a query -
SELECT * FROM TABLE WHERE Date >= DATEADD (day, -7, -getdate()) AND Date <= getdate();
This would return all records for each day except day 7. If I ran this query on a Sunday at 17:00 it would only produce results going back to Monday 17:00. How could I include results from Monday 08:00.
Try it like this:
SELECT *
FROM SomeWhere
WHERE [Date] > DATEADD(HOUR,8,DATEADD(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))) --7 days back, 8 o'clock
AND [Date] <= GETDATE(); --now
That's because you are comparing date+time, not only date.
If you want to include all days, you can trunc the time-portion from getdate(): you can accomplish that with a conversion to date:
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -convert(date, getdate())
AND Date <= convert(date, getdate());
If you want to start from 8 in the morning, the best is to add again 8 hours to getdate.
declare #t datetime = dateadd(HH, 8, convert(datetime, convert(date, getdate())))
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -#t) AND Date <= #t;
NOTE: with the conversion convert(date, getdate()) you get a datatype date and you cannot add hours directly to it; you must re-convert it to datetime.
Sounds like you want to remove the time. Correct? If so then do the following.
SELECT * FROM TABLE WHERE Date >= (DATEADD (day, -7, -getdate()) AND Date DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))

How to get 00:00:00 in datetime, for First of Month?

I wrote a query to obtain First of month,
SELECT DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as First_Of_Month;
for which i do get the appropriate output, but my time stamp shows the current time.
Here's what I am doing in the query, hope i make sense.
using datepart i calculated the no. of days (int) between the 1st and today (27-1 =26)
Then using dateadd function, i added "-datepart" to get the first of the month.
This is just changing the date, what should i look at or read about in order to change the time. I am assuming that it would have something to do with 19000101
For SQL Server 2012 (thanks adrift and i-one)
DECLARE #now DATETIME = CURRENT_TIMESTAMP;
SELECT DATEADD(DAY, 1, EOMONTH(#now, -1));
-- or
SELECT DATEFROMPARTS(YEAR(#now), MONTH(#now), 1);
For SQL Server 2008+
DECLARE #now DATETIME = CURRENT_TIMESTAMP;
-- This shorthand works:
SELECT CONVERT(DATE, #now+1-DAY(#now));
-- But I prefer to be more explicit, instead of relying on
-- shorthand date math (which doesn't work in all scenarios):
SELECT CONVERT(DATE, DATEADD(DAY, 1-DAY(#now), #now));
For SQL Server 2005
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0);
A caveat if you're using this SQL Server 2005 method: you need to be careful about using expressions involving DATEDIFF in queries. SQL Server can transpose the arguments and lead to horrible estimates - as seen here. It might actually be safer to take the slightly less efficient string approach:
SELECT CONVERT(DATETIME, CONVERT(CHAR(6), GETDATE(), 112) + '01');
SELECT convert(varchar(10),DATEADD(DAY, - (DATEPART(DAY,GETDATE())-1), GETDATE()),120)+' 00:00:00' as First_Of_Month;
Just the date
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
So for a month it is:
DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0) AS FirstDatetimeOfMonthmm,
I think the easiest way is to cast the result to date:
SELECT cast(DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as date) as First_Of_Month
One alternative:
SELECT cast(
cast(datepart(yyyy, getdate()) as varchar)
+ '-'
+ cast(datepart(mm, getdate()) as varchar) + '-01 00:00:00'
as datetime)
Build up the date from year/month components, then tack on the 1st and midnight.
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) as First_Of_Month;
Try following code:
SELECT CAST(CAST(GETDATE() AS DATE) AS DATETIME) AS StartDateTime,
DATEADD(ms, -3, CAST(CONVERT(date, DATEADD (DAY,1,GETDATE())) AS varchar(10))) AS EndDateTime
Result:
StartDateTime
EndDateTime
2022-05-23 00:00:00.000
2022-05-23 23:59:59.997

How to select date without time in SQL

When I select date in SQL it is returned as 2011-02-25 21:17:33.933. But I need only the Date part, that is 2011-02-25. How can I do this?
For SQL Server 2008:
Convert(date, getdate())
Please refer to https://learn.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql
I guess he wants a string.
select convert(varchar(10), '2011-02-25 21:17:33.933', 120)
120 here tells the convert function that we pass the input date in the following format: yyyy-mm-dd hh:mi:ss.
Using CAST(GETDATE() As Date) worked for me
The fastest is datediff, e.g.
select dateadd(d, datediff(d,0, [datecolumn]), 0), other..
from tbl
But if you only need to use the value, then you can skip the dateadd, e.g.
select ...
WHERE somedate <= datediff(d, 0, getdate())
where the expression datediff(d, 0, getdate()) is sufficient to return today's date without time portion.
CAST(
FLOOR(
CAST( GETDATE() AS FLOAT )
)
AS DATETIME
)
http://www.bennadel.com/blog/122-Getting-Only-the-Date-Part-of-a-Date-Time-Stamp-in-SQL-Server.htm
For 2008 older version :
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
you can use like this
SELECT Convert(varchar(10), GETDATE(),120)
In case if you need the time to be zeros like 2018-01-17 00:00:00.000:
SELECT CONVERT(DATETIME, CONVERT(DATE, GETDATE()), 121)
I would use DATEFROMPARTS function. It is quite easy and you don't need casting. As an example this query :
Select DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE())) as myNewDate
will return
2021-01-21
The good part you can also create you own date, for example you want first day of a month as a date, than you can just use like below:
Select DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) as myNewDate
The result will be:
2021-01-01
You can try this one too.
SELECT CONVERT(DATE, GETDATE(), 120)
Its too late but following worked for me well
declare #vCurrentDate date=getutcdate()
select #vCurrentDate
When data type is date, hours would be truncated
It's a bit late, but use the ODBC "curdate" function (angle brackes 'fn' is the ODBC function escape sequence).
SELECT {fn curdate()}
Output: 2013-02-01
Convert it back to datetime after converting to date in order to keep same datatime if needed
select Convert(datetime, Convert(date, getdate()) )
If you want to return a date type as just a date use
CONVERT(date, SYSDATETIME())
or
SELECT CONVERT(date,SYSDATETIME())
or
DECLARE #DateOnly Datetime
SET #DateOnly=CONVERT(date,SYSDATETIME())
Use is simple:
convert(date, Btch_Time)
Example below:
Table:
Efft_d Loan_I Loan_Purp_Type_C Orig_LTV Curr_LTV Schd_LTV Un_drwn_Bal_a Btch_Time Strm_I Btch_Ins_I
2014-05-31 200312500 HL03 NULL 1.0000 1.0000 1.0000 2014-06-17 11:10:57.330 1005 24851e0a-53983699-14b4-69109
Select * from helios.dbo.CBA_SRD_Loan where Loan_I in ('200312500') and convert(date, Btch_Time) = '2014-06-17'
select DATE(field) from table;
field value: 2020-12-15 12:19:00
select value: 2020-12-15
In PLSQL you can use
to_char(SYSDATE,'dd/mm/yyyy')
First Convert the date to float (which displays the numeric), then ROUND the numeric to 0 decimal points, then convert that to datetime.
convert(datetime,round(convert(float,orderdate,101),0) ,101)
Try this.
SELECT DATEADD(DD, 0, DATEDIFF(DD, 0, GETDATE()))
I would create a scalar function and use format () to set the datatype you want to see. It is must easy on the maintenance later.
Personal favorite:
select convert(datetime, convert(int, getdate()))