April 11, 2014 at 4:42 pm
Hi Team,
I have couple of datetime fields in a table called "Appointment". They are Appstart and AppEnd.
I want to find the difference between these two fields in MINS and in HOURS as separate columns.
How can achieve this?
regards,
April 11, 2014 at 5:51 pm
Use the function DATEDIFF ( datepart , startdate , enddate ) it is in BOL (Books On Line) if you need to see examples of its use
April 11, 2014 at 5:58 pm
I'm sure there's other ways, but here's what first came to mind:
create table #Appointment (AppStartDate datetime, AppEndDate datetime)
insert into #Appointment values('1/1/2014 8:30am', '1/1/2014 9:45 am')
select
*,
floor((CONVERT(float, AppEndDate) - CONVERT(float, AppStartDate)) * 24) hrs,
((CONVERT(float, AppEndDate) - CONVERT(float, AppStartDate)) * 24 - floor((CONVERT(float, AppEndDate) - CONVERT(float, AppStartDate)) * 24)) * 60 mins
from #Appointment
..or use DATEDIFF as bitbucket suggested 😉
April 11, 2014 at 6:44 pm
Becareful using DATEDIFF for the calculation of durations. The difference between 11:59PM and 12:00AM according to DATEDIFF is an hour because DATEDIFF doesn't calculate durations... it simply calculates the number of boundaries crossed.
--Jeff Moden
Change is inevitable... Change for the better is not.
April 11, 2014 at 7:24 pm
Try this:
create table #Appointment (AppStartDate datetime, AppEndDate datetime);
insert into #Appointment values('1/1/2014 8:30am', '1/1/2014 9:45 am');
select
*,
datediff(minute,AppStartDate,AppEndDate) / 60 hrs,
datediff(minute,AppStartDate,AppEndDate) % 60 mins
from #Appointment;
drop table #Appointment;
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply