DATEDIFF Getting the previous month - sql

I want to get the previous month relative to the current date
SELECT datediff(mm,-1,2-2-2011)
This query gives 67 which is a wrong value .. where i went wrong ?

You can use DATEADD
eg.
SELECT DATEADD(month, -1, GETDATE())

This 2-2-2011 is not a valid date literal - you are subtracting 2 from 2 and then 2011 from the result - proper date literals are '2-2-2011' and #2-2-2011#. You can use GETDATE() to get the current date, instead of relying on a literal.
Nor should you be using DATEDIFF - it gives you the difference between dates.
You should be using DATEADD to calculate new dates.
Try this:
SELECT DATEADD(mm,-1, GETDATE())
This will get the date a month ago.
If you just want the month, you need to also use DATEPART:
SELECT DATEPART(mm, SELECT DATEADD(mm,-1, GETDATE()))

SELECT datepart(mm, dateadd(mm,-1,'2011/1/1') )

If you want the month before the current month, you want
SELECT MONTH(DATEADD(mm, -1, GETDATE()))
If you want the date for a month before the current date, you want
SELECT DATEADD(mm, -1, GETDATE())
BTW, SELECT datediff(mm,-1,2-2-2011) computes the number of months between day -1 and day -2011, which is 67 (2010 / 30). That's nowhere near what you seem to actually want.

You need to use DATEADD - not DATEDIFF
DATEDIFF calculates the difference between two dates - it doesn't add day or months to an existing date....
Also, you need to put your dates into single quotes: use '2-2-2011' instead of simply 2-2-2011.
And lastly: I would strongly recommend using the ISO-8601 date format YYYYMMDD (here: 20110202) - it will work regardless of the language and regional settings on your SQL Server - your date format will BREAK on many servers due to language settings.

DATEDIFF calculates the difference between your stating and ending dates
every date previous to the current date has a positive number and every date next to the current date has negative number, this works in geting your specific date weather it a day,month,year or hour to understand this better below is the syntax of datediff
DATEDIFF (your datetime type, your starting date,your ending date)
the function does (your ending date)-(your starting date)
in your case the below datediff will work just pefectly
SELECT DATEDIFF (month,[you_date_or_datetime_column],GETDATE()) = 1

You can use DATEADD try this code
For previous month
SELECT DATEADD(month, -1, GETDATE())
For 7 day previous
$date = date('Y-m-d',strtotime("-7 days"));
SELECT * FROM users WHERE `date` LIKE '%$date%'
$date varibale get previous date date

Related

<Resolved> Fetch last date of a month and last minute of that day

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

How to get the records of last month in SQL Server?

I want to get the records of last month based on my table [Sales], variable "SoldDate" in SQL Server.
For example, if today is 29/09/2021, I want to get the data for 01/08/2021-31/08/2021
The "SoldDate" variable is in the format 2018-04-11 00:00:00.000.
I would really appreciate your help! I have no idea how to get this to work :(
You can use eomonth() :
SELECT DATEADD(DAY, 1, EOMONTH(SoldDate, -2)) AS StartDate, EOMONTH(SoldDate, -1) AS EndDate
The best way to search through an indexed table is to calculate what date range you need, and filter on that. You can use DATEADD and EOMONTH for this. Note that since you have a time component, you cannot just use EOMONTH
SELECT *
FROM YourTable
WHERE SoldDate >= DATEADD(day, 1, EOMONTH(GETDATE(), -2))
AND SoldDate < DATEADD(day, 1, EOMONTH(GETDATE(), -1))
EOMONTH gives you the end of a month, the second parameter denotes how many months to shift.
Note correct use of the half-open interval >= AND <, this dealls correctly with the time component.

Selecting Dynamic date in a date range of sql

This is what my query's date range is:
WHERE
date BETWEEN 20190101 AND [here date should come as last year YTD -1]
For example if we use this query today (20201106) (format:yyyymmdd), then the 2nd date should be 20191105.
For more clarity: when I run this query today (20201106) my query should fetch results from date range:
WHERE
date BETWEEN 20190101 AND 20191105
When I run this query tomorrow (20201107), my query should fetch results from the date range:
WHERE
date BETWEEN 20190101 AND 20191106
How can I do this?
Can anyone help?
you can use dateadd() with getdate()
DATEADD(year,-1, GETDATE())
or other function that can get current database time but this should work.
also remember to use convert() to modify the date format into what you want.
WHERE
DATEADD(YEAR,-1, GETDATE()) -- One Day Before Today in the Last Year
AND
DATEADD(yy, DATEDIFF(yy, 0, DATEADD(YEAR,-1, GETDATE())), 0) AS StartOfYear -- The Day 1 of the Last Year
I would phrase this as:
where date >= datefromparts(year(getdate()) - 1, 1, 1)
and date < dateadd(year, -1, convert(date, getdate()))
This filters from the start of last year and the 1 year and 1 day ago.
Note that I changed the filtering strategy to use half-open intervals rather than between. This is somehow more flexible, as it would properly handle a time component in in date, if any, and simplifies the offsetting logic.
Note also that getdate() has a time component, that needs to be removed while offsetting to implement your logic.

SQL datediff with negative parameter

I am a complete noob to SQL and trying to understand why this query returns "115":
select datediff(yy, -3, getdate())
datediff takes three Parameter. The first is the interval, the second the start date and the third the end date. You are passing -3 as start date, there we can show:
SELECT CAST(-3 AS datetime) -- results in '1899-12-29 00:00:00.000'
And because 2014 - 1899 is 115, you will get this as result.
Because DATEDIFF() calculates an interval between 2 dates, and you specified year -3 in one of them.
Firstly, the date "zero" is 12/30/1899 on SQL server.
Secondly, your "-3" was an incorrect date format and it thus replaced it with its 0
2014 - 1899 = 115
Use DATEADD() instead to achieve what you want to do.
DateDiff gives difference in years/date/months etc based on what you have given in first parameter. second and third parameter are datetime values which will be used to calculate the difference i.e. (param2 datetime value - param3 datetime value).
Now in your case param2 is "-3"
run this queries in you ms sql and observe the outputs :
select CAST(-3 as datetime)
select GETDATE()
select datediff(yy, -3, getdate())

How to check if a datetime variable occurs in the past twelve months

What I am trying to do is to see if a datetime variable has the value of a date at anytime in the past twelve months.
I tried using the DATEDIFF function but then I quickly discovered that this has rounding problems (a comparison between 31st DEC/1st JAN would count as 1 month for example, despite the fact only a day has passed between them)
To make this more accurate I could use -365 days as a parameter rather than -12 months however this still gives the problem of not taking into account leap years (not a common scenario but still one I'd ideally avoid!)
Any ideas as to how I can best go about this?
The problem with leap years can be solved with the DATEADD (datepart , number , date ) function. You can specify minus one year from the current date.
where myDate between DATEADD (year , -1 , GETDATE() ) and GETDATE()
Use DATEADD instead to subtract a year from today and compare that
#datetimevariable >= DATEADD(year, -1, GETDATE())
Note: you don't need to compare the upper bound (GETDATE()) unless you have dates in the future.
Also, do you want exactly one year down to the hour and minute? If not, use this which is safe for datatype precedence if #datetimevariable is datetime or datetime2, and you need this is a WHERE clause or such
#datetimevariable >= CAST(DATEADD(year, -1, GETDATE()) as date)
This works for leap years
SELECT DATEADD(YEAR, -1, '20120301'), DATEADD(YEAR, -1, '20120229')
2011-03-01 00:00:00.000
2011-02-28 00:00:00.000
DATEDIFF works on specific boundary: start of month, start of year, midnight etc which is why it fails in this case
DATEDIFF counts the number of partitions between the two dates, sorry to say there is no rounding issue, it does exactly what it says on the tin. YOUR best solution is probably to used DATEADD
WHERE MyVal BETWEEN GETDATE() AND DATEADD(YEAR, -1, GETDATE())