I have the following piece of SQL:
select DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
which comes through as this format:
2012-02-29 23:59:59.000
I need the exact piece of code with the date the same, however the time part must read 00:00:00.000
Modify* I should have been clear here: I need to have the last day of previous month at any given time (with the time in 00:00:00.000 format of course)
select dateadd(d,datediff(d,0,dateadd(s,-1,dateadd(m,datediff(m,0,getdate()),0))),0)
SELECT DATEADD(MONTH, -1, DATEADD(DAY, 0, DATEDIFF(DAY, 0, GETDATE())))
This will give you the last second of the prior month
select dateadd(s,-1,dateadd(month,datediff(month,0,GETDATE()),0));
and this will give you the last day of the prior month
select dateadd(day,-1,dateadd(month,datediff(month,0,GETDATE()),0));
More details of how to do this:
select dateadd(day,datediff(day,0,#datetime),0);
or
select dateadd(day,datediff(day,0,GETDATE()),0);
In English: Take the number of days between this date and 0 and add those days to 0.
This works with any parameter for datediff. So
select dateadd(month,datediff(month,0,GETDATE()),0);
Will "remove" all day information in addition to time information.
An alternative method to strip out the time portion is to cast it to a float, apply the Floor function and cast back to a datetime.
select Cast(Floor(Cast(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) as float)) as datetime)
SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
In SQL Server 2012 you could use eomonth.
SELECT EOMONTH(DATEADD(MONTH, -1, GETDATE()))
Saw some similar posts
select cast(cast(dateadd(dd,-1,getdate()) as date) as datetime)
Cast your dateadd as a date and then enclose it in another cast back to datetime
So it goes from this
2012-02-29 23:59:59.000
To this
2012-02-29
and the finally this
2012-02-29 00:00:00.000
Related
I need to get last day of the month with time like
2023-01-31 23:59:59:000000
I'm able to get only the last day of the month with time stamp as
2023-01-31 00:00:00:000000
As jarlh said your best method is to add a day to the end of the month, then subtract a second (although if you really want the absolute maximum time I think you'd want to subtract 3 milliseconds).
EOMONTH -> Add 1 day -> Cast as datetime -> remove 1 second / 3 milliseconds. You have to cast as datetime because the EOMONTH function implicitly casts to a date
The code will be something like this:
SELECT DATEADD(SECOND, -1, CAST(DATEADD(DAY, 1, EOMONTH(#currentDate)) AS DATETIME))
SELECT DATEADD(MILLISECOND, -3, CAST(DATEADD(DAY, 1, EOMONTH(#currentDate)) AS DATETIME))
There are already similar questions with a lot of answers. You should find your anwer for sure:
Get the last day of the month in SQL
SQL query to display end date of current month
DECLARE #currentDate DATE = GETDATE()
SELECT EOMONTH (#currentDate) AS CurrentMonthED
SQL query to display end date of Next month
DECLARE #currentDate DATE = GETDATE()
SELECT EOMONTH (#currentDate, 1 ) AS NextMonthED
I'm working in SQL Server 2014 and need calculate exactly one month previous from a SQL Server DateTime, but I'm unable figure out how to use DATEADD correctly.
Examples:
SELECT DATEADD(MONTH, -1, '20200229')
returns 2020-01-29.
SELECT DATEADD(MONTH, -1, '20200301')
returns 2020-02-01.
But in this second statement, I would like to get 2020-01-30 and 2020-01-31
Any ideas?
Seems you want end of previous month, in that case add EOMONTH() to your script which goes as follows
Select EOMONTH( DATEADD(MONTH,-1,'20200229'));
Select EOMONTH( DATEADD(MONTH,-1,'20200301'));
From the docs:
If the following are true:
datepart is month the date month has more days than the return month
the date day does not exist in the return month
Then, DATEADD returns the last day of the return month.
For example, September has 30 (thirty) days; therefore, these statements return 2006-09-30 00:00:00.000:
SELECT DATEADD(month, 1, '20060830');
SELECT DATEADD(month, 1, '20060831');
2020 is a Leap Year. Most of the time your 2/29 would not work anyway.
Also there is no 2/30 & 2/31 so 1/30 & 1/31 would not appear.
Use the EOMONTH() function with the optional second parameter, which is an int and is the number of months difference to the date:
select eomonth('2020-02-29', -1);
Returns:
2020-01-31
Kindly try this.
SELECT DATEADD(DAY,1,DATEADD(MONTH, -1, '20200229')), DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, DATEADD(MONTH, -2, '20200301')) + 1, 0))
I wish to pull three years of data from a database but right now I have to specify the dates in a number of sections in my code using a between statement:
BETWEEN '2015-10-01' AND '2018-09-30'
Since the database only contains valid data from the previous month backwards, I wish to take the end of the last month and go back three years.
I found this tutorial where the author shows how to do this in SQL server and I've tried to adapt it but my RDBMS is throwing errors in the datediff function
----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
My code looks as follows but I the error I am seeing is about converting 0 to a date.
DECLARE #date DATE
SET #date = getdate()
SELECT dateadd(second,-1,dateadd(mm, DATEDIFF(m,0,GETDATE()),0))
If anyone has any suggestions I would be very grateful for your guidance.
In your WHERE clause, you could use this condition:
DATEDIFF(month, [YourDateColumn], GETDATE()) BETWEEN 1 AND 36
Your current code looks good without any error, but you can use EOMONTH() instead.
However, the difference would be in return types your code would return date-time while eomonth() would return date only.
DECLARE #date DATE
SET #date = getdate()
SELECT EOMONTH(#date, -1)
Don't use between and the job becomes far easier. Use less than the first day of the current month which accurately locates everything before that date (instead of last day of previous month). Subtract 3 years from that same date and use >= for the starting point.
Select *
From yourtables
where datecol >= dateadd (year,-3,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0) )
And datecol < DATEADD(mm,DATEDIFF(m,0,GETDATE()),0)
Please don't use any solution that use 23:59:59 as the end of a day. It is not the end of a day and several data types now support sub-second time precision.
If you really cannot use zero in the date functions simply use the base date of '1900-01-01' instead
SELECT
DATEADD(YEAR, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), '1900-01-01'))
, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), '1900-01-01')
;
This should also work (it does in this demo here):
SELECT
DATEADD(YEAR, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), 0))
, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), 0)
;
I have the following sql which returns the date of last monday.
SELECT DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0) //2017-05-15 00:00:00.000
However in trying to understand how this has been worked out, I'm confused
as to what the 6124 returned by the following represents
SELECT DATEDIFF(wk, 6, GETDATE())
It's only last week why is it such a high number?
Also how can the offset be a fixed number and still be able to work out the date of the previous monday
That's sunday of Jan of 1900...
SELECT
DATEDIFF(wk, '1/1/1900','5/20/2017'),
DATEDIFF(wk, '1/1/1900',GETDATE())
Specifically, they are using DATETIMEOFFSET instead of an actual DATETIME which is an acceptable parameter of DATEDIFF
So to answer you question, that's the number of weeks (since you specified wk) from the first Sunday in January 1900 to the current day.
The parameter of 6 for startdate in the datediff is just another way to reduce the output by one week, so it returns how many weeks since 1900-01-06 instead of 1900-01-01 (difference of one).
These two statements will return the same result:
select dateadd(week, datediff(week, 6, getdate()),0)
select dateadd(week, datediff(week, 0, getdate())-1,0)
Just this part: datediff(week, 6, getdate() returns the number of weeks (6,124) since 1900-01-06 which when added to a date of 1900-01-01 gives you the start of last week.
If I have a date value like 2010-03-01 17:34:12.018
What is the most efficient way to turn this into 2010-03-01 00:00:00.000?
As a secondary question, what is the best way to emulate Oracle's TRUNC function, which will allow you to truncate at Year, Quarter, Month, Week, Day, Hour, Minute, and Second boundaries?
To round to the nearest whole day, there are three approaches in wide use. The first one uses datediff to find the number of days since the 0 datetime. The 0 datetime corresponds to the 1st of January, 1900. By adding the day difference to the start date, you've rounded to a whole day;
select dateadd(d, 0, datediff(d, 0, getdate()))
The second method is text based: it truncates the text description with varchar(10), leaving only the date part:
select convert(varchar(10),getdate(),111)
The third method uses the fact that a datetime is really a floating point representing the number of days since 1900. So by rounding it to a whole number, for example using floor, you get the start of the day:
select cast(floor(cast(getdate() as float)) as datetime)
To answer your second question, the start of the week is trickier. One way is to subtract the day-of-the-week:
select dateadd(dd, 1 - datepart(dw, getdate()), getdate())
This returns a time part too, so you'd have to combine it with one of the time-stripping methods to get to the first date. For example, with #start_of_day as a variable for readability:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(dd, 1 - datepart(dw, #start_of_day), #start_of_day)
The start of the year, month, hour and minute still work with the "difference since 1900" approach:
select dateadd(yy, datediff(yy, 0, getdate()), 0)
select dateadd(m, datediff(m, 0, getdate()), 0)
select dateadd(hh, datediff(hh, 0, getdate()), 0)
select dateadd(mi, datediff(mi, 0, getdate()), 0)
Rounding by second requires a different approach, since the number of seconds since 0 gives an overflow. One way around that is using the start of the day, instead of 1900, as a reference date:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(s, datediff(s, #start_of_day, getdate()), #start_of_day)
To round by 5 minutes, adjust the minute rounding method. Take the quotient of the minute difference, for example using /5*5:
select dateadd(mi, datediff(mi,0,getdate())/5*5, 0)
This works for quarters and half hours as well.
If you are using SQL Server 2008+, you can use the Date datatype like this:
select cast(getdate() as date)
If you still need your value to be a DateTime datatype, you can do this:
select cast(cast(getdate() as date) as datetime)
A method that should work on all versions of SQL Server is:
select cast(floor(cast(getdate() as float)) as datetime)
Try:
SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
UPDATE: answer on the second question:
for years you could use a little bit modified version of my answer:
SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
for quarter:
SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
and so on.
I checked, up to minutes - it's OK. But on seconds I've got an overflow message:
Difference of two datetime columns
caused overflow at runtime.
One more update: take a look to the following answer to the same question
This is late, but will produce the exact results requested in the post. I also feel it is much more intuitive than using dateadd, but that is my preference.
declare #SomeDate datetime = '2010-03-01 17:34:12.018'
SELECT
DATEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01'
) AS CUR_DATE_FROM_PARTS
,DATETIMEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01' --DAY(#SomeDate)
,'00' --DATEPART(HOUR,#SomeDate)
,'00' --DATEPART(MINUTE,#SomeDate)
,'00' --DATEPART(SECOND,#SomeDate)
,'00' --DATEPART(MILLISECOND,#SomeDate)
) AS CUR_DATETIME_FROM_PARTS
,#SomeDate AS CUR_DATETIME
,YEAR(#SomeDate) AS CUR_YEAR
,MONTH(#SomeDate) AS CUR_MONTH
,DAY(#SomeDate) AS CUR_DAY
,DATEPART(HOUR,#SomeDate) AS CUR_HOUR
,DATEPART(MINUTE,#SomeDate) AS CUR_MINUTE
,DATEPART(SECOND,#SomeDate) AS CUR_SECOND
,DATEPART(MILLISECOND,#SomeDate) AS CUR_MILLISECOND
FROM Your_Table
Truncated Date: 2010-03-01
Truncated DateTime: 2010-03-01 00:00:00.000
DateTime: 2010-03-01 17:34:12.017
Not sure if this is the most efficient, but I like the simplicity in using the following where #SomeDate is your field.
Concat(Year(#SomeDate), '-', Month(#SomeDate), '-', '01')
If you want to truncate a date to the start of the week in a way that is independent of SET DATEFIRST you can:
--change a date backwards to nearest Monday
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN)
Breaking this down:
DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN): the dw of a known Monday (2001-01-01 was a Monday) minus the dw of your date, effectively giving the "number of days difference between your date and Monday" or "how many days back do we have to scroll your date to make it into Monday"
( ... -7)%7 - we subtract 7 from it and modulo the result by 7.
We do this because if e.g. DATEFIRST is 7 (Sunday), and your date column is Sunday then your dw is 1, and your known Monday is 2.
This means the result of the dw_for_known_monday - dw_for_your_date is +1 rather than -6
This would then mean that DATEADD will roll your date forwards to the following Monday rather than backwards to the previous Monday
If we subtract 7 off it then the result would definitely be negative, but then we wouldn't want your Mondays (which are 0 days different from the known Monday) to end up doing a DATEADD of -7, so we modulo the result by 7.
This turns any problematic -7 into 0, which means your DATEADD will only ever have a "number of days" argument between -6 and 0
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN) - we then DATEADD the (negative) number of days from the above step
If you want to roll your date backwards to e.g. a Sunday, change the date 2001-01-01 to a date that is a known Sunday (like 2000-12-31), etc