Date difference in Days,hours minutes and seconds.

Hi All,
I have two date Suppose one is getdate() and other one is gatedate() +1 .I have to show the difference, currently I used a datediff in the stored proc which just shows the difference of the days :( but i need to show the difference in days:hours:minutes:seconds if possible.
its a countdown with the current date. Like the two fields are sale_start_date and sale_end_date. Hope i am clear.
Please let me know ASAP thanks in advance.Can anyone help me?all help is great help.
Say the difference of
12/6/2007 7:00:00 AM, 12/8/2007 8:00:00 AM  as 2 days 1:00:00)
Thanks
N

One of the problems of using DATEDIFF when dealing with either seconds or milliseconds is that this function will result in execution errors if the start and end dates span then entire domain of possible dates.  Below is an alternative that seems to work over the entire date domain.  A couple of things to note:
1. This select converts the days and seconds of each date into BIGINT datatypes to avoid the overflow error
2. This select uses a CROSS APPLY operator; in this case I chose CROSS APPLY to suggest the possibility of converting this select into an inline table function.
I suspect that if you dig around this forum and the net that you will find a better routine, but here is yet another alternative:
declare @test table
( startDate datetime, endDate datetime)
insert into @test values
('6/1/9', getdate()),
('6/9/9 15:15', '6/10/9 19:25:27.122'),
('6/9/9 15:15', '6/10/9 13:25:27.122'),
('6/9/9', '6/10/9 00:00:01'),
('1/1/1760', '12/31/2999')
select
  startDate,
  endDate,
  [Days],
  [Hours],
  [Minutes],
  [Seconds]
from @test
cross apply
( select
    cast((endSecond - startSecond) / 86400 as integer) as [Days],
    cast(((endSecond - startSecond) % 86400) / 3600 as tinyint) as [Hours],
    cast(((endSecond - startSecond) % 3600) / 60 as tinyint) as [Minutes],
    cast((endSecond - startSecond) % 60 as tinyint) as [Seconds]
  from
  ( select
      86400 * cast(convert(integer, convert(binary(4),
                    left(convert(binary(8), startDate),4))) as bigint)
        + cast(convert(integer, convert(binary(4),
            right(convert(binary(8), startDate),4)))/300 as bigint)
      as startSecond,
      86400 * cast(convert(integer, convert(binary(4),
                    left(convert(binary(8), endDate),4))) as bigint)
        + cast(convert(integer, convert(binary(4),
            right(convert(binary(8), endDate),4)))/300 as bigint)
      as endSecond
  ) q
) p
/* -------- Sample Output: --------
startDate               endDate                 Days        Hours Minutes Seconds
2009-06-01 00:00:00.000 2009-06-22 08:28:36.670 21          8     28      36
2009-06-09 15:15:00.000 2009-06-10 19:25:27.123 1           4     10      27
2009-06-09 15:15:00.000 2009-06-10 13:25:27.123 0           22    10      27
2009-06-09 00:00:00.000 2009-06-10 00:00:01.000 1           0     0       1
1760-01-01 00:00:00.000 2999-12-31 00:00:00.000 452900      0     0       0
(5 row(s) affected)
 EDIT:
I based the routine more-or-less on Thilla's reply.
Kent Waldrop

Similar Messages

  • How to get two date difference in Day/hour/min/secs pl

    First of all,
    Hello to All, i am new to Oracle DB, but i have little experience in Other Database such as Sybase, sql server etc
    please kindly help me
    in DoctorChart table i have DocName,Id#,Citcotype,Medtype,AdmitDate,DischargeDate(both admitdate & Discharge date is date formatted columns)
    so how can i get the below differenceTime (which means Dischargedate-Admit Date in below format i.e, Day,Hours,Minutes,Seconds...)
    DoctorName, ID #, Citco type, MEDtype, DifferenceTime
    ========= === ======= ======= ===========
    Dr. KindaEmesko, 20045, Replace OutCard, ICH, 0 day 9 hours 11 minutes
    Dr. KindaEmesko, 20098, Replace OutCard, ICH, 1 day 2 hours 34 minutes
    Dr. KindaEmesko, 20678, Replace OutCard, ICH, 2 day 23 hours 52 minutes
    Dr. KindaEmesko, 20212, Replace OutCard, ICH, 4 day 1 hours 00 minutes
    Dr. KindaEmesko, 20345, Replace OutCard, BED, 3 days 14 hours 15 minutes
    Dr. KindaEmesko, 20678, Replace OutCard, BED, 9 days 21 hours 52 minutes
    Dr. KindaEmesko, 20015, Signature Overlay, Rest, 0 days 3 hours 29 minutes
    Dr. KindaEmesko, 45678, Signature Overlay, Rest, 0 days 1 hours 29 minutes
    Same way how can i get the Average Time for the above result (without ID columns)
    DoctorName, Citco type, MEDtype, Avg DifferenceTime
    ========= === ======= ======= ===========
    Dr. KindaEmesko, Replace OutCard, ICH, 2 day 1 hours 00 minutes
    Dr. KindaEmesko, Replace OutCard, BED, 6 days 17 hours 15 minutes
    Dr. KindaEmesko, Signature Overlay, Rest, 0 days 2 hours 29 minutes
    Please just tell me how to get the two dates difference as day/hour/minute format
    as well as how to get avg ( two dates difference as day/hour/minute format)
    Please Help me
    Thanks in advance

    Well, instead of all these suggested manipulations you can simply use intervals. Oracle uses day as a unit in date arithmetic, so Dischargedate-Admit Date is number od days between two dates. Built-in function numtodsinterval can be used to convert it into interval. For example:
    SQL> with t as (
      2             select trunc(sysdate) - 2 Admit_Date,
      3                    sysdate            Discharge_Date
      4               from dual
      5            )
      6  select  numtodsinterval(Discharge_Date - Admit_Date,'DAY') Hospital_Stay
      7    from  t
      8  /
    HOSPITAL_STAY
    +000000002 00:01:08.000000000
    SQL>  SY.

  • How do I log the time in hours, minutes and seconds to a table

    Hi
    I'm a relatively new user of Labview. I am currently writing a program that logs the temperature of an oven and the current time to a table and graph. I am using a GPIB card to communicate with the oven. I have used the Get Date/Time string to get the time and the Decimal String to Number to convert the time to a number which I have then put into an array which goes to a table and graph. My problem at the moment is that the time is being logged in hours only. I need to log the time in hours, minutes and seconds. Can you tell me how I can do this?

    Hi,
    I can see the setup now. The decimal string to number will only ever give the hours, since the ':' character is not part of a number, so won't translate. Use the code I attached previously to get the time as a timestamp, and then go from there.
    I've made some modifications, although you'll need to alter the file save to take into account the double precision number
    for the timestamp is now 3E+9 (since it's seconds since 1904!!), but since you're writing to a comma separated values (or tab deliminated) style file, this shouldn't be a problem. You could always do a textual save from the table instead.
    Thanks
    Sacha Emery
    National Instruments (UK)
    // it takes almost no time to rate an answer
    Attachments:
    temp time program.vi ‏98 KB

  • SharePoint DateTime Control "Hour, Minute, and Second parameters describe an un-representable DateTime"

    I am facing a strange behavior from SharePoint:DateTime control.
    I have a webpart containing couple of fields along with datetime control. If I leave this page inactive for a while and then click submit, an exception is thrown stating that "Hour, Minute, and Second parameters describe an un-representable DateTime". 

    Hi,
    According to your post, my understanding is that you got datetime control error.
    The problem may be lied in the Time component. You can disable the time component and go for a date only rendering of the control by setting
    DateTimeField.DateOnly = true.
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/64c05363-fd7e-49bb-8239-c93ec78172b6/datetime-control-using-basefieldcontrol?forum=sharepointgeneralprevious
    what’s  more, you can the ULS log to see the details errors.
    For SharePoint 2013, by default, ULS log is at
    C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\LOGS
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • Formula for Distance/Velocity Returned in Hours, Minutes, and Seconds

    I want to find the formula to calculate elapsed time in hours, minutes, and seconds when you are given the velocity and distance.

    Distance(Miles)
    MPH
    Duration(h, min, s)
    60,0
    20,30
    0
    100,0
    20,80
    For an unknown reason the formula do not work for me.
    Cells A2, B2, A3, and B3 are numbers.
    In cell C2 I use formula : =DURATION(0,0,A2/B2)
    Thanks
    Carougeois

  • I need help to convert hours,minutes and seconds to seconds.

    Hi, I need help with the code on how to convert the hours,minutes and seconds to seconds. I don't know which formula to use so that I can get the results in total number of seconds. Thanks.

    Jos ("when in doubt: parenthesize correctly")Bracist.You're more right than you'd known: last week I climbed over a safety
    fence (which I wasn't supposed to do of course) to adjust the position
    of an optical measurement device we installed in a huge production
    machine in a factory. I stepped on some sort of hose; the end of that
    hose broke loose and hit me straight in the middle of my lower jaw. My
    front teeth feel wiggly now and my molars on the left of my lower jaw are
    not what they used to be. This Wednesday I get that all fixed at some
    dental clinic. Keep your fingers crossed because me+dentists == war.
    My tongue continuously keeps on reporting craters and disaster ;-)
    Jos, how's it going? Besides a possible loss of some teeth, I'm fine ;-)
    My Spring/Hibernate journey continues. I'm trying out Hibernate 3.2
    annotations and the Ant tools. So far, so good.Good to hear. At the moment I'm putting my teeth (sic) in that darn snmp
    stuff which simply refuses to work the way I want it and besides that I'm
    heavily involved in some of that SAP stuff. Spring is not in the vicinity for
    me in the next couple of months sadly enough.
    kind regards,
    Jos

  • How to conver this System.nanoTime() into Hours,minutes and second

    I am getting my Total time with the help of this function ie System.nanoTime(). But i want to Display in the form of Hours,minutes and second.
    So can any one plz tell me that how i will do this conversion.

    If it's less than 24 hours you can use Calendar. or SimpleDateFormat. Add the epoch time for some convenient midnight to the milliseconds value (divide nanos by 1000000).
    Otherwise it's just successive division and remaindering.
    Probably nanos is higher resolution than you need, milliseconds is easier.

  • Insert hour, minute and seconds in database

    I need to work with a date with this format:
    22/dec/2000:09:10:55
    My problem is:
    I don't now how to insert it in my database. If I declare a field date it doesn't works, even if i use To_date.
    if I declare a field varchar2 I cant do operation like the difference between hours and minutes.
    Thanks.
    I work with oracle7.

    Internally oracle stores a date variable in
    integer form and hence the format is irrelevant. You can use any format that includes second's and minutes, as you need it.
    What matters is how you retrieve it.
    While retrieving it if you put the fetched value in date variable then things are fine, but if you want it in char / varchar then use
    to_date('date_field','<format>')
    I feel what you are trying to do is select on sql prompt and see the min and seconds.
    I suggest you check your nls_date_format parameter on sql environment for your default date format.
    You could set it according to your need like this
    alter session set nls_date_format='dd-mon-yyyy hh24:mi:ss';
    null

  • How to get time in hours minutes and seconds subtract between two varchar t

    Hi all,
    I have two varchar variable which has value like this
    v_outpunch1:='17:50:00'
    and v_Shifttime:='18:00:00'
    this both time i am subtracting here and storing in another varchar variable
    which is like this.
    v_EarlyLeaverstimeformat := LPAD((extract(hour from TO_TIMESTAMP (v_ShiftTime,'HH24:mi:ss')) - extract(hour from TO_TIMESTAMP (v_OutPunch1,'HH24:mi:ss'))), 2, '0')||':'|| LPAD((extract(minute from TO_TIMESTAMP (v_ShiftTime,'HH24:mi:ss')) - extract(minute from TO_TIMESTAMP (v_OutPunch1,'HH24:mi:ss'))), 2, '0')||':'|| LPAD((extract(second from TO_TIMESTAMP (v_ShiftTime,'HH24:mi:ss')) - extract(second from TO_TIMESTAMP (v_OutPunch1,'HH24:mi:ss'))), 2, '0');
    it's not subtracting value correctly.
    thanks

    You shouldn't store time information in a varchar2, but if you do
    declare
      v_outpunch1 varchar2(100);
      v_Shifttime varchar2(100);
      v_EarlyLeaverstimeformat varchar2(100);
    begin
      v_outpunch1:='17:50:23';
      v_Shifttime:='18:00:00';
      v_EarlyLeaverstimeformat := numtodsinterval( to_date( v_Shifttime, 'hh24:mi:ss' ) - to_date( v_outpunch1, 'hh24:mi:ss' ), 'day' );
      dbms_output.put_line( v_EarlyLeaverstimeformat );
      v_EarlyLeaverstimeformat := to_char( trunc( sysdate ) + ( to_date( v_Shifttime, 'hh24:mi:ss' ) - to_date( v_outpunch1, 'hh24:mi:ss' ) ), 'hh24:mi:ss' );
      dbms_output.put_line( v_EarlyLeaverstimeformat );
    end;

  • DateValidator and inputFormat, I would like to check hour minute and second too

    Hi this is my control and I would like to validate the whole
    date not just YYYYMMDD
    <mx:DateValidator id="dateVal" source="{TI_FechaInicio}"
    property="text" inputFormat="yyyy-mm-dd L:NN:SS A"/>
    But it doesn't seems to work, so how can I fix it?
    The only working thing are yyyy-mm-dd but (L:NN:SS A) none of
    those ones work

    Thanks again, I've read your link and I also had a
    RegularExpression that I used on .NET but here in flex doesn't
    seems to work, I've tested this Regular Expression and its working
    but not in flex, do you know what I'm doing wrong?
    <mx:RegExpValidator id="REV_FechaInicio"
    source="{TI_FechaInicio}" property="text"
    expression="^(19[0-9]{2}|[2-9][0-9]{3})-((0(1|3|5|7|8)|10|12)-(0[1-9]|1[0-9]|2[0-9]|3[0-1 ])|(0(4|6|9)|11)-(0[1-9]|1[0-9]|2[0-9]|30)|(02)-(0[1-9]|1[0-9]|2[0-9]))\x20(0[0-9]|1[0-9]| 2[0-3])(:[0-5][0-9]){2}(?:\x20[aApP][mM])$"
    trigger="{B_Actualizar}" triggerEvent="click"
    noMatchError="Fecha no válida" />
    <mx:Form width="95%">
    <mx:FormItem label="Fecha Inicio (mm/dd/yyyy):"
    width="100%">
    <mx:TextInput id="TI_FechaInicio" />
    </mx:FormItem>
    <mx:FormItem>
    <mx:Button id="B_Actualizar" label="Actualizar"
    click="Submit();"/>
    </mx:FormItem>
    </mx:Form>

  • Calculating Hour, Minutes, or Seconds differences between dates

    How can I calculate the hour, minutes or second differences between two dates.

    I have found the following in another thread of the forum.
    http://forum.java.sun.com/thread.jsp?forum=16&thread=437334&tstart=0&trange=30
    import java.util.*;
    final class DHMS {
    public static int[] toDhms(long millis){
        int[] dhms = new int[4];
        long d = millis /(1000L*60*60*24);
        long h = (millis - d*(1000L*60*60*24)) /(1000L*60*60);
        long m = ((millis - d*(1000L*60*60*24)) - h*(1000L*60*60)) /(1000L*60);
        long s = ((millis - d*(1000L*60*60*24)) - h*(1000L*60*60) - m*(1000L*60)) /1000L;
        dhms[0]=(int)d;
        dhms[1]=(int)h;
        dhms[2]=(int)m;
        dhms[3]=(int)s;
        return dhms;
    public static void main(String[] args){
    Calendar cal = Calendar.getInstance();
    cal.setLenient(false);
    Date date0= cal.getTime();
    // .. for example ..//
    cal.add(GregorianCalendar.DATE,(int)(365)); // a year
    cal.add(GregorianCalendar.HOUR,4);
    cal.add(GregorianCalendar.MINUTE,20);
    cal.add(GregorianCalendar.SECOND,80); //(60 + 20) seconds
    Date date1 = cal.getTime();
    int[] result=DHMS.toDhms(date1.getTime() - date0.getTime());
    for(int i=0;i<result.length;i++) {// set your pattern
        switch(i){
           case 0: System.out.print("Days: "); break;
           case 1: System.out.print("Hours: ");  break;
           case 2: System.out.print("Minutes: "); break;
           case 3: System.out.print("Seconds: "); break;
           default: break;
           System.out.println(Integer.toString(result));

  • I am looking for a timer that shows elapsed time since a particular date and time.  Showing days, hours, minutes etc.

    I would like to download an application for my desktop and maybe even my iphone that will tell me how many days, hours, minutes, etc have elapsed since a particular date.
    For example, my brother just had a baby and I want to put that date and time into the app and then determine how long it has been since that date and time.
    Hopefully this makes sense, because I have not been able to locate anything.
    Thanks in advance,

    This is fantastic.  Thank you.
    Is there any way to have something like this displayed on my desktop showing the time as it ticks away?

  • Adding day/hour/minute/second to a date value

    How does one add a day/hour/minute/second to a date value?

    SQL> select to_char(sysdate, 'DD/MM/YYYY HH24:MI:SS') to_day,
      2         to_char(sysdate+1, 'DD/MM/YYYY HH24:MI:SS') add_day,
      3         to_char(sysdate + 1/24, 'DD/MM/YYYY HH24:MI:SS') add_hour,
      4         to_char(sysdate + 1/(24*60), 'DD/MM/YYYY HH24:MI:SS') add_minute,
      5         to_char(sysdate + 1/(24*60*60), 'DD/MM/YYYY HH24:MI:SS') add_second
      6  from dual
      7  /
    TO_DAY              ADD_DAY             ADD_HOUR            ADD_MINUTE          ADD_SECOND
    10/10/2006 11:54:23 11/10/2006 11:54:23 10/10/2006 12:54:23 10/10/2006 11:55:23 10/10/2006 11:54:24
    SQL>Cheers
    Sarma.

  • Latest itunes shows silly days approximation instead of days, hours, minutes, seconds, how do i change back?

    itune 11.0.0.163 shows silly date approximation on bottom bar rather than days, hours, minutes, seconds as before. How do I change this?

    Apple buried the transfer purchases option, but it's still there. To transfer purchases from your iOS device in iTunes:
    Select the device toward the top-middle of iTunes (underneath the status area/progress bar/Apple logo).
    Go to the File menu.
    Select Devices
    Click on Transfer Purchases from [DeviceName]...

  • Converting seconds to Days,Hours,mins and secs

    Hi gurus,
    I have a metric in seconds , which is a box uptime . I want to convert that into Days,hours , mins and secs .How can I do that ?
    For example , If I have 433500 secs , I should show it as 5days 00:25:00 or in some meaningful format . Can anyone help me out ?
    Thanks,

    Hi,
    Refer thinks,
    Re: seconds to hh:mm:ss format
    OBIEE 11g - Change seconds to DD HH:MM:SS format
    Deva

Maybe you are looking for

  • Adobe air installer problem. app behaving strange

    Hi all i developed a desktop app in flex..In this i set the alpha of a text input /text area to alpha=0 .the app is behaving different..on different pc's..i executed to debug the app on my pc on setting the alpha=0 for text input the background becom

  • Drag-and-drop tree list from files/folder

    Hello all. I'm new to Flex and I'm looking for some help or for someone to point me in the right direction. I want to write a simple AIR application to accept a multiple text files (or a folder full of text files) when the files/folder is dragged int

  • Cannot Update Transitions

    I am working on Final Cut Studio, and have been going along just fine with inserting simple transitions, such as 1 second cross dissolves. Then, when I try to continue doing that, even though I have plenty of footage on either side, the transition in

  • Custom file info panel visable in bridge?

    I have created a file info panel for CS2 using xml and saved it as a .txt file format. This is now visible and usable in all CS2, can be saved, and is also visible through Portfolio 8. However, I have opened the test file in Bridge and am unable to v

  • There are no colors in my ipod

    my ipod is only black and white... i dont know why... please help me...