How to calculate DateDiff in minutes correctly? - sql

I'm trying to find a way to calculate minutes between 2 times using DATEDIFF
SELECT DATEDIFF(minute, CAST('05:00:00' AS time), CAST('23:59:00' AS time))
This returns 1139 which is correct but when I do
SELECT DATEDIFF(minute, CAST('05:00:00' AS time), CAST('00:37:00' AS time))
I get -263.
I have different data with different end dates in my database, and my question is how can I use single query to calculate the minutes correctly for both the cases?

There is no issue in this case.
5 AM is after Midnight (and 37 minutes).
Every day starts at 00:00:00.000 and ends up at 23:59:59.999.
Because you specified only the time, it cannot understand that you need the day after.
I suggest you to specify the date as well:
SELECT DATEDIFF(minute, CAST('2022-11-22 05:00:00' AS datetime), CAST('2022-11-23 00:37:00.000' AS datetime))

Related

Show time difference in minutes

I need to calculate the time differences on a given day. I tried something like that but not works.
CONVERT(TIME, DATEADD(MINUTE, DATEDIFF(MI, MIN(CreatedOn),
MAX(CreatedOn)), 0), 108) AS WorkingTime
Thanks guys
You can try this way, since you don't show the error you get I don't know what detail you can have, but to get the time difference you can get it like this as I leave you here below
DECLARE #MaxDate DATETIME=DATEADD(HOUR,20,GETDATE()) --here you could get the maximum of your table separately
DECLARE #MinDate DATETIME=GETDATE() --here you could get the minimum of your table separately
SELECT DATEDIFF(MINUTE,#MinDate,#MaxDate) AS WorkingTime
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=09128de0d996e85a21992197b524a208
Your question is not entirely clear, but I think this is what you're trying to do.
SELECT CAST(WorkingTime AS DATE),
MIN(WorkingTime) AS min,
MAX(WorkingTime) AS max,
DATEADD(HOUR, DATEDIFF(HOUR, 0, MIN(WorkingTime)), 0) AS truncatedmin,
DATEDIFF(MINUTE,DATEADD(HOUR, DATEDIFF(HOUR, 0, MIN(WorkingTime)), 0),MAX(WorkingTime)) AS [difference]
FROM YourTable
GROUP BY CAST(WorkingTime AS DATE)
The column called "difference" should show the number of minutes difference between the truncatedmin and max columns.
From this column I need to calculate the working time for each day, for this I need to select the first time on a given day and then round it to the full hour (06:08:20 to 06:00:00) and then calculate the differences between the last time in day, which will give me the working time in minutes.
My column

SQL Server - check if store is open

I have a table as below
StoreName | TimeOpens | DurationInMinutes | DayOfTheWeek
Dog Store '00:08:00.000' 400 1
Duck Store '00:08:00.000' 1300 1
Cat Store '00:08:00.000' 1440 1
I need to select all stores that are currently open. Times are stored in UTC so GETUTCDATE() can be used to get current time. The TimeOpens is a Time object and not a DATETIME, which is why I am a little confused how to write a query that will get me the correct answer. The scenarios are what if the time overlaps over midnight because the duration is that long as in case of Duck Store or what if the duration is 1440 minutes long meaning that its open 24 hours a day.
I thought about converting it to a DateTime first which would make things easier but then I'm not sure do I get today's date or yesterdays when calculating this. For example if I get today's date and its past midnight then I'm before the store opened which would mean its closed. I have the same problem with choosing the day of the week as if its past midnight its technically next day but it could still be open from previous day.
SELECT *
FROM Stores
WHERE GETUTCDATE() > CAST(LEFT(CONVERT(DATE, GETUTCDATE()), 10) + ' ' + LEFT(CONVERT(VARCHAR, S.[TimeOpens], 120), 12) AS DATETIME)
Edit, the query should somehow include dayoftheweek as well because each day could have a different schedule. its a 1-7 index.
You can do:
where (cast(getutcdate() as time) >= timeopens and
datediff(minute, cast(getutcdate() as time), timeopens) <= duration
) or
(cast(utcdate() as time) < dateadd(minute, duration, timeopens) and
day(dateadd(minute, duration, cast(timeopens as datetime))) > 0
)
you can use this condition to get if its still a valid opening hours.
SELECT *
FROM Stores
WHERE
datediff(mi,
dateadd(mi, DurationInMinutes,cast(concat(convert(DATE, getutcdate()), ' ', TimeOpens) as datetime))
, getutcdate()) < 0

sql statement - would like to subtract 1 date from another and get the days hours and mins inbetween

I would like to subtract 1 date from another and get the days hours and mins in-between.
I know there is a DateDiff function, however it does not work with all 3 time values; days hours and mins. I would like this doable in an SQL statement. Currently I have the following.
SELECT id, pickupdateandtime, GETDATE() AS CurrentTime,
(DATEDIFF(day,GETDATE(),pickupdateandtime)) AS Days,
(DATEDIFF(hour,GETDATE(),pickupdateandtime)) AS Hours,
(DATEDIFF(minute,GETDATE(),pickupdateandtime)) AS Mins FROM orders
And it shows up like this:
If we can stick it all in 1 column that's fine too.
I agree with #AndyMcLaughlin about the use of the mod operator % here. It's very handy for this sort of thing. However, I have a general distrust of DATEDIFF. That function does not count the whole number of years (say) between two dates, but the number of year boundaries between them.
So DATEDIFF "thinks" the difference in years between 01-Jan-2000 and 01-Jan-2001 is the same as that between 31-Dec-2000 and 01-Jan-2001.
This is why #Michael saw a need to subtract 1 from #AndyMcLaughlin's results. Unfortunately, that doesn't always work, it will depend on the individual case.
As a rule, DATEDIFF works well when it's used against the smallest interval you are interested in. So if you are interested in years and simply want to separate one calendar year from another, it'll serve you well.
I think the smallest interval we are interested in here is minutes. So we can use DATEDIFF for that, but have to work upwards from there to hours and days:
select
mf.id,
mf.pickupdateandtime,
mf.CurrentTime,
--The divisions in the following lines simply
--truncate since all the numbers are integers
--but that works in our favour here
(mf.MinutesFull/(60*24)) as Days,
(mf.MinutesFull/60) % 24 as Hours,
mf.MinutesFull % 60 as Minutes
from
(
select
id,
pickupdateandtime,
getdate() as CurrentTime,
datediff(minute, getdate(), pickupdateandtime) as MinutesFull
from #orders
) mf
You need to use the mod operator % to remove whole days from hours and whole hours from minutes.
So you can do something like:
SELECT
id,
pickupdateandtime,
GETDATE() AS CurrentTime,
(DATEDIFF(day,GETDATE(),pickupdateandtime)) AS Days,
(DATEDIFF(hour,GETDATE(),pickupdateandtime) % 24) AS Hours,
(DATEDIFF(minute,GETDATE(),pickupdateandtime) % 60) AS Mins FROM orders

how to show float numbers in Hours, Day, Minute, Second in SQL Server

I have a simple record in table below:
Depart_dt Arrived_dt
10/1/2013 6:15:00 AM 10/1/2013 7:25:00 AM
Based on my calculation, it is 1 hour and 10 min.
Thanks to VKP, I used the datediff function as below:
Select
Dateiff (DD, depart_dt, arrived_dt) as day,
Dateiff (HH, depart_dt, arrived_dt) as hour,
Dateiff (Minute, depart_dt, arrived_dt) as min,
Date if (second, depart_dt, arrived_dt) as second
from temp
However, my result looks funny with the minute and second columns
Day Hour Min Second
0 1 70 4200
The hour appears correct but I am not sure how it comes to 70 in min column and 4200 in second column?
sorry guys, I was wrong. Yes, 70 min is correct because that is 1 hour and 10 min. Please disregard this
You can just use DATEDIFF to get the difference as an integer.
select item,
datediff(dd, start_dt, end_dt) as total_days,
datediff(hh, start_dt, end_dt) as total_hours,
datediff(minute, start_dt, end_dt) as total_minutes,
datediff(second, start_dt, end_dt) as total_seconds
from yourtable
When using datediff you'll have to understand what it does. The name is quite confusing, because it doesn't actually calculate date differences, but according the documentation: "Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate."
That means that for example datediff hour for 06:15 and 07:00 is 1 hour.
You'll probably want something like this:
DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])/86400 as Days,
((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)/3600) as Hours,
(((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)%3600)/60) as Minutes,
(((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)%3600)%60) as Seconds
This calculates the amounts in full days / hours etc so number of hours will never be 24 or more.

How to get total number of hours between two dates in sql server?

Consider two dates 2010-03-18 22:30:45 and 2010-03-19 03:30:15 .... How to get the number of hours and minutes in between the two dates in sql server.....
#codeka answered with the hours part (from your title) but in the body of your question you asked for hours and minutes so, here is one way
select DATEDIFF(hh, #date1, #date2) as Hours_Difference,
DATEDIFF(mi,DATEADD(hh,DATEDIFF(hh, #date1, #date2),#date1),#date2) as Minutes_Difference
What this does in the first part is what #codeka showed. It gives you the datediff between the two dates in actual full hours. The second term in the sql gives the datediff in minutes between the (first date + the hours elapsed) and the second date. You have to eliminate the hours from the equation in the minutes part or you will get the actual minutes between the dates. Datediff and its allowed Datepart identifiers can be researched here:
http://msdn.microsoft.com/en-us/library/ms189794.aspx
You want the DATEDIFF function:
SELECT DATEDIFF(hh, #date1, #date2)
The problem with William Salzman's answer is that it returns strange answers if the first time is not on the hour. So 10:30 to 12:00 gives 2 hours and -30 minutes.
If that isn't what you want, then this will give you 1 hour and 30 minutes:
select
CONVERT(int,DATEDIFF(mi, #date1, #date2) / 60) as Hrs_Difference,
CONVERT(int,DATEDIFF(mi, #date1, #date2) % 60) as Mins_Difference
DATEDIFF function will solve your problem of getting hours difference.
you can check this as :
select DATEDIFF(hh, getdate()-1, GETDATE()) HoursDifference
It will give you result of 24 hours
Thanks
It seems there are various ways to answer this, but for me, I've always believe in the notion of starting small - as in get the overall value and then convert it UP to the answer you want.
Assuming date2 is greater than date1:
A simple mathematical difference multiplied by 24 hours in a day works:
CAST(date2 - date1 as NUMERIC(18,4)) * 24.00 AS [HrsDiff]
Or using Will's answer using [min] for minutes:
CAST(DATEDIFF(mi, date1, date2) AS NUMERIC(18,4)) / 60 AS [HrsDiff]
So the minute total is divided by 60 to give you the hours.
The first option gives you a big decimal, whereas the 2nd option rounds it up to the nearest decimal.