Round a timestamp - sql

I would like to differentiate between two dates and round the result to the next day.
For exemple, if I have date1='2020-03-10 11:59:00' and date2='2020-03-10 20:53:00', the difference between date1 and date2 with datediff() is equal to 8 hours. I would like to round this result to have 24 hours.
EDIT
I tried by using dateadd() like this :
select DATEADD(HOUR, DATEDIFF(HOUR, '2020-03-10 11:59:00', '2020-03-10 20:53:00'),0)
Return 1900-01-02 09:00:00.000 doesn't correspond to what I want.

The explanation of the output is not at all clear so I am just guessing here. I am taking the difference in days between two dates. Then adding 1 because if two dates are the same day the difference in days is 0. Then multiplying that result by 24. I changed up the date literal so it is ANSI compliant and will always get the correct date regardless of localization or language settings.
declare #date1 datetime = '20201003 11:59:00'
, #date2 datetime = '20201003 20:53:00'
select datediff(day, #date1, #date2) + 1 * 24

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

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

Confusion over the second argument of the DATEDIFF function

I've referred to this on MSDN but I'm still unsure what the second argument in the DATEDIFF function is doing in the following two examples:
SELECT DATEDIFF(yy,0,getdate()) --run on 14 Aug this returns 112
SELECT DATEDIFF(yy,1000,getdate()) --I chose 1000 arbitrarily and run on 14 Aug this returns 110
Usually I'll use DATEDIFF to find the number of days, or number of years between two months and the second argument is then a date.
Reason I'd like to understand the above is to ultimately understand the following:
SELECT DATEADD(yy, DATEDIFF(yy,0,GETDATE()), 0)
If you use an integer as the second argument (or for any datetime/smalldatetime assignment for that matter), this is interpreted as the number of days since 1900-01-01.
DECLARE #d1 DATETIME = 0, #d2 DATETIME = 1;
SELECT #d1, #d2;
Result:
1900-01-01 00:00:00.000 1900-01-02 00:00:00.000
Note that this doesn't work for new data types like DATE during direct assignment:
DECLARE #d DATE = 0;
Result:
Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with date
But it can still work using date math, e.g.:
DECLARE #d DATE = DATEADD(YEAR, 0, SYSDATETIME());
SELECT #d;
Result:
2012-08-14
For these inconsistent reasons, I recommend you use proper date literals so that it is clear which date you mean and so that it works regardless of the data type. This is a habit I find hard to break, since typing 0 is so much easier than 19000101...
Consider below example to understand this concept better. 0 is default date "1900-01-01"
Below Query gives output as 2017-10-31 00:00:00.000
SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH,0,SYSDATETIME())+3, 0))
Dividing the above query into various parts to understand the calculation.
-- 1414 Months since '1900-01-01'
SELECT DATEDIFF(MONTH,0,SYSDATETIME()) + 3
-- adding 1414 Months to Default date 1900 Produces '2017-11-01 00:00:00.000'
SELECT DATEADD(MONTH, DATEDIFF(MONTH,0,SYSDATETIME())+3, 0)
--Subtract 1 day from '2017-11-01 00:00:00:000' gives last day of previous month.
SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH,0,SYSDATETIME())+3, 0))
The second argument to datediff() is a date.
The first example returns the "start" date of time in the SQL Server world. That would be 112 years before the current date.
The second example is rather non-sensical. As implemented, the dates are represented as number days since the earliest date. This is the number of years since 1000 days after the earliest date.
The last example adds a number of years to the base date. It then adds a number of months. Since the base date is 1/1/1900, this is giving you the first date of the day after the nth month in the yth year.

DATEDIFF Getting the previous month

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

Is there a way to subtract an amount of days from a date in SQL?

I know about DATEDIFF(d, date1, date2), but I am not looking to subtract two dates, rather an amount of days from a date.
For example:
"2010-04-13" - 4 = "2010-04-09"
Is that possible with mySQL?
date_sub(date,interval 4 day);
Yes. See http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_adddate
SELECT DATE_ADD('2008-01-02', 31);
Results in:
'2008-02-02'
To subtract, just use a negative number, or use DATE_SUB
This will subtract 2 days from a date in a table, and show both dates.
SELECT
[Date]
,DATEADD(DAY, -2, [Date]) AS [NewDate]
FROM
[YourTable]
yes. Mysql has plenty of date functions. Just google mysql datetime functions and you'll get the list. Date subtraction ones among them