Difference between two dates: a complete solution

There have been many posts asking how to get the number of days between two dates. There is no method in java like the VB method dateDiff(), and there is only the method date.getTime() which gives you the number of milliseconds since Jan 1 1970, the Epoch. I have not seen a solution that makes use of the fact that there are 86400000 milliseconds per day, only when trying to get the number of days , i.e. multiples of 24 hours between two millisecond points in time.
So what if date1 was Oct 26th 11.30pm and date2 was Oct 27th 12.30am? If you get the millisecond difference, and divide by 86400000, you do not notice that these two times are on separate days, but only one hour apart.
My solution takes account of the modulo (%) function. If you use the date.getTime() method, and use % 86400000 on this number of milliseconds, it will tell you how far (milliseconds) this date is into this day, after 12am. If you subtract this amount from the total number of milliseconds, then divide by 86400000, this will give you the number of days after the Epoch, so you are able to know which day the millisecond time is in. If you want to know the days between two millisecond times, this will tell you, whereas just dividing by 86400000, will not, and may be misleading.
I think this could be incorporated into the Date class easily. There are some problems though, as not every day has 86400000 milliseconds, if you are talking about days when Daylight Saying Time begins or ends. Doing calculations like that will create errors, unless you know whether each date is in Daylight Saving Time or not. Leap years are OK, unless want to work out the number of years from the number of days by dividing by 365, as calculating numbers of days is only done by looking at a 24 hour time period. However where 'leap seconds' have been added, like once every ten years, there may be small errors. This was not included in anyone elses calculations.
So the calculation would go like this:
public class BetterDate extends Date
public int dayDifference(Date d)
long time = this.getTime() ; // gets milliseconds
long timed = d.getTime() ; // gets milliseconds of other date
int days = (time - (time % 86400000))/86400000 ; // number of days
int daysd = (timed - (timed % 86400000))/86400000 ; // number of days of other date
int difference = daysd - days ; // difference in days between two dates
return difference ;
If you want you can use the value (time % 86400000), and modulo this amount with the number of milliseconds in one hour, then subtract the result from the (time % 86400000) and divide by the millliseconds in one hour to give you the number of hours, but there are JDK functions that you can use to get the hour if needed.
This method is not perfect, but for most cases will get you the difference in days between two dates.
James

Hi James,
I tried out your solution, but it seems to fail on dates without times. I tries the difference between 31/03/2002 and 01/04/2002 and the result is 0. I guess it is because the times are assumed to be 00:00 as no times are mentioned and 31st March I believe is the date when DST change will take place this year. If I set the two times as well to a time much later than midnight for example 0600 then I seem to get the right answer.
Joag
There have been many posts asking how to get the
number of days between two dates. There is no method
in java like the VB method dateDiff(), and there is
only the method date.getTime() which gives you the
number of milliseconds since Jan 1 1970, the Epoch. I
have not seen a solution that makes use of the fact
that there are 86400000 milliseconds per day, only
when trying to get the number of days , i.e. multiples
of 24 hours between two millisecond points in time.
So what if date1 was Oct 26th 11.30pm and date2 was
Oct 27th 12.30am? If you get the millisecond
difference, and divide by 86400000, you do not notice
that these two times are on separate days, but only
one hour apart.
My solution takes account of the modulo (%) function.
If you use the date.getTime() method, and use %
86400000 on this number of milliseconds, it will tell
you how far (milliseconds) this date is into this day,
after 12am. If you subtract this amount from the total
number of milliseconds, then divide by 86400000, this
will give you the number of days after the Epoch, so
you are able to know which day the millisecond time is
in. If you want to know the days between two
millisecond times, this will tell you, whereas just
dividing by 86400000, will not, and may be
misleading.
I think this could be incorporated into the Date class
easily. There are some problems though, as not every
day has 86400000 milliseconds, if you are talking
about days when Daylight Saying Time begins or ends.
Doing calculations like that will create errors,
unless you know whether each date is in Daylight
Saving Time or not. Leap years are OK, unless want to
work out the number of years from the number of days
by dividing by 365, as calculating numbers of days is
only done by looking at a 24 hour time period. However
where 'leap seconds' have been added, like once every
ten years, there may be small errors. This was not
included in anyone elses calculations.
So the calculation would go like this:
public class BetterDate extends Date
public int dayDifference(Date d)
long time = this.getTime() ; // gets milliseconds
long timed = d.getTime() ; // gets milliseconds of
other date
int days = (time - (time % 86400000))/86400000 ; //
number of days
int daysd = (timed - (timed % 86400000))/86400000 ; //
number of days of other date
int difference = daysd - days ; // difference in days
between two dates
return difference ;
If you want you can use the value (time % 86400000),
and modulo this amount with the number of milliseconds
in one hour, then subtract the result from the (time %
86400000) and divide by the millliseconds in one hour
to give you the number of hours, but there are JDK
functions that you can use to get the hour if needed.
This method is not perfect, but for most cases will
get you the difference in days between two dates.
James

Similar Messages

  • Difference between two dates into server behaviors

    Good morning all,
    I'm trying to create a recordset using server behaviors and as I'm not an expert using php I'm completely lost...
    The problem is the following : I want to find into a table all the records where the difference between today date and their creation date (stored in that table of course) is greater than, let's say 30days. How can I indicate that into the variables field ?
    Many thanks in advance for your help !

    Many thanks !
    I was ignoring the DATE_SUB function and it does work in such a simple way… (with a closing parenthesis at the end)
    Thanks again !
    Best regards
    De : osgood_ [email protected]
    Envoyé : lundi 16 septembre 2013 15:59
    À : Berurier75
    Objet : Difference between two dates into server behaviors
    Re: Difference between two dates into server behaviors
    created by osgood_ <http://forums.adobe.com/people/osgood_>  in Dreamweaver support forum - View the full discussion <http://forums.adobe.com/message/5685549#5685549

  • Difference between two date

    Hi All ,
    Please suggest me Function module which will give me difference between two date and time.
    I have tried various FMs they all are giving difference in days and hours but I want to know difference in seconds also.
    Thanks in advance.
    Regards ,
    Jigar Thakkar.
    Moderator message: please look even further or simply program your own little solution.
    Edited by: Thomas Zloch on Mar 11, 2011 10:47 AM

    Michael,
    For VB.net the date difference method is the same as it is for VBA. Depending on whether you want working days or calendar days, the methods are:
    Difference in working days:
    Application.DateDifference(StartDate, FinishDate, Calendar)
    Difference in calendar days:
    DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])
    You can also use these same formula in a custom field in Project.
    Hope this helps.
    John

  • Calculate the difference between two dates

    I would like to calculate the difference between two dates in PL/SQL and return the result as a number of days expressed as an integer value.

    Denes,
    A fair point, I should really have posted this on the SQL forum (I'm new to the forum as well as PL/SQL) but thanks for responding anyway. It does raise a question as to how to implement this in ApEx though.
    I have created the function and am calling it as shown below from the source window of a form. The source type is 'PL/SQL expression or function' and the expression in the source window of the form is:
    calc_date_difference (:p26_c_payment, :p26_c_rec)
    The two parameters being passed are of type date but I'm not sure how to handle the ruturned number and populate the form in ApEx with this value.
    Is it possible to do it this way or am I taking completely the wrong approach?
    Regards
    Sandy
    This is not ApEx related but SQL related:
    CREATE OR REPLACE FUNCTION calc_date_difference (
    p_date_1   VARCHAR2,
    p_date_2   VARCHAR2
    RETURN NUMBER
    v_difference   NUMBER;
    v_sql_err      VARCHAR2 (4000);
    BEGIN
    v_difference := TRUNC (TO_DATE (p_date_1)) - TRUNC
    (TO_DATE (p_date_2));
    RETURN v_difference;
    CEPTION
    WHEN OTHERS
    THEN
    v_sql_err := SQLERRM || CHR (10) || CHR (10) ||
    SQLCODE;
    ND calc_date_difference;and
    SQL> SELECT calc_date_difference ('23.01.2007',
    '20.01.2007') diff
    2    FROM DUAL;
    DIFF
    3
    Denes Kubicek                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • As to the data type of the data type of the difference between two date type of datas

    Hi,
    I have a question about the data type of the difference between two date type of datas.
    There are two date type of datas as:
    SSHIPMENTS.RECEIVEDATETIME
    SSHIPMENTS.PROMISEDATETIME
    I try to use the following SQL Script in Oracle SQL*Plus as:
    SELECT CASE
    WHEN (SSHIPMENTS.RECEIVEDATETIME - SSHIPMENTS.PROMISEDATETIME) < '000 01:00:00.000' THEN 'OnTime'
    WHEN (SSHIPMENTS.RECEIVEDATETIME - SSHIPMENTS.PROMISEDATETIME) < '000 01:30:00.000' THEN '60-89 Minutes'
    ELSE '3+ Hours'
    END
    FROM SSHIPMENTS;
    The error message of "Invalid Number" for the '000 01:30:00.000' happens.
    I don't know if the data type of the interval is wrong.
    Many Thanks,
    Cathy

    SELECT CASE
    WHEN (to_char(SSHIPMENTS.RECEIVEDATETIME,'hhmiss') - to_char(SSHIPMENTS.PROMISEDATETIME,'hh24miss')) < '010000' THEN 'OnTime'
    WHEN (to_char(SSHIPMENTS.RECEIVEDATETIME,'hhmiss') - to_char(SSHIPMENTS.PROMISEDATETIME,'hh24miss'))< '000 01:30:00.000' THEN '60-89 Minutes'
    ELSE '3+ Hours'
    END
    FROM SSHIPMENTS;
    just try it out..

  • Date difference between two dates

    hi All,
    i have to right a stored proc to find the difference between two dates. 
    for example of i give
    startdate as 4/1/2015 and enddate 14/1/2015
    i should get 1 year , 10 days and 0 months .
    i have tried the DateDiff function but it does not calculate the leap year.
    please help.

    DECLARE @from datetime
    DECLARE @to   datetime
    SET @from = '20150104  8:00'
    SET @to   = '20150114  10:30'
    SELECT DATEDIFF(minute,@from, @to) % 60 as Minutes
    SELECT (DATEDIFF(minute,@from, @to) / 60) % 24 as Hours
    SELECT DATEDIFF(minute,@from, @to) / (60 * 24) as Days
    SELECT DATEDIFF(month,@from, @to) as Months
    SELECT DATEDIFF(year,@from, @to) as Year
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Difference between two date in bex query

    Hi all,
    I need to do a difference between two date using formula variable processing type customer exit beaucause I must use factory calendar in the formula.
    How can I do it?
    Can you give me an example of the routine?
    Thanks a lot
    Gianmarco

    Hi,
    You can still use the same code to copy it and customize as per your need. All you need to do is to subract the dates using the class: CL_ABAP_TSTMP after converting to timestamp and resulting seconds you convert back to days....Please get help from the developers to do this...
    Also, ensure that you write back this difference value to your variable so you get it on the reports for your calculations...
    Cheers,
    Emmanuel.

  • Difference between two dates

    Hi
    I have two date fields in the ODS..Both are characterists
    1. Requested delivery date
    2. Actual shipment end date.
    I would like to create a calculated KF  field for the difference between two dates in a query.
    How can I accomplish it?
    Regards

    You have to make Expiration data as nav attribute and create a formula variable then only this date can be used in calculations.
    refer this How to...for the same
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/72f4a790-0201-0010-5b89-a42a32223ffc
    later you can try to calculate difference between dates!
    Re: calculating the difference between two dates
    Please search in forum with 'difference between two dates'.You will find lots of good posts on this issue!
    hope this helps
    Regards

  • Calculate the Difference Between two dates excluding weekends and Holidays

    Hi,
    We need to calculate the difference between the two dates by excluding the Local public holidays (It is global and varies across countries) and weekends should not be included in calculation for a business day in OBIEE.
    We have two dates: Open date and close date when ever close date is null we are calculating age based on taking the current timestamp and need to exclude the weekends and Holidays when ever the close date is null.
    Ex:
    Col1 col2 Total
    11/9/2010 2:46:38 PM Null 13
    11/2/2010 8:06:26 PM 11/3/2010 5:37:03 PM 1
    (In the Total we shouldn't include the weekends,holidays)
    Please let me know how to calculate the difference between two dates by excluding the weekends and holidays.
    Thanks
    Edited by: user10441472 on Nov 22, 2010 3:14 PM

    You already asked this question and I answered it...
    Re: calculation of Business day in OBIEE

  • How to get the difference between two date

    Hello,
    I want to know how to write a code the tell me the difference between two date, I am using
    oracle.jbo.domain.Date
    i have a rent date and return date so my code is
    Date rent=(Date)nr.getAttrbute("RentDate"),ret=(Date)nr.getAttrbute("ReturnDate");
    is there a way to know the difference in days between those two dates ?
    Thanks

    hi,
    try this.....
    DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    Date date = (Date)formatter.parse(dateStr); //// dateStr <- from date value (that is string value)
    Date dateto = (Date)formatter.parse(datetostr); //// datetostr <- to date value (to date getting from as a string)
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    Calendar calto = Calendar.getInstance();
    calto.setTime(dateto);
    fromDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
    toDate = calto.get(Calendar.DATE) + "/" + (calto.get(Calendar.MONTH) + 1) + "/" + calto.get(Calendar.YEAR);
    // System.out.println("from Date : " + fromDate);
    if ((fromDate != null && toDate != null) && (date.compareTo(dateto) > -1) ) {                  
    fc.addMessage("VacationQueryComponent", new FacesMessage(FacesMessage.SEVERITY_ERROR, "From Date cannot be lower than To Date", "From Date cannot be lower than To Date"));
    fc.renderResponse();
    thks.

  • Java code to get the difference between two dates in days

    Hi ppl,
    I need to write a user defined function to get the difference between two date nodes, in days.Please help me out
    regards,
    Prashanth

    Hi,
    have a look at those two:
    (How do I calculate the difference between two dates?)
    http://joda-time.sourceforge.net/faq.html
    Calculating the Difference Between Two Datetime Stamps
    http://www.xmission.com/~goodhill/dates/deltaDates.html
    Get difference in days
    http://javaalmanac.com/egs/java.util/CompDates.html
    Regards,
    michal

  • Difference between Two Date Should come into Text Item

    Dear All,
    i want to get difference between two date into text Item :P36_C in On Change java script.
    i have two Date Item :P36_A and :P36_B .i have extract these date value from table then difference comes into Text Field :P36_C.
    Now i want if i change Date into Item :P36_A or Item :P36_B then Defference between two date Should Come into Item :P36_C .
    So i have use Java Script Code to do this
    <script>
      function diffdat(){
        function getVal(item){
       if($x(item).value != "")
         return parseFloat($x(item).value);
       else
         return 0;
        $x('P36_C').value =
    getval((TO_DATE('P36_B', 'DD-MON-YYYY'))-
    getval(TO_DATE('P36_A', 'DD-MON-YYYY')))+1;
    </script>
    i have put this into Item HTML Form Element Attributes 
    onChange="javascript:diffdat();"it's not woring .
    How to work that Code with dates.
    Thanks

    You can always create your own difference function based on your own criteria. You can modify this to suit your needs.
    CREATE OR REPLACE FUNCTION CALC_OFFICE_DAYS(date1 DATE, date2 DATE)
    RETURN NUMBER
    IS
    v_begin_date DATE := date1;
    v_end_date DATE := date2;
    v_office_start_time VARCHAR2(10) := '09:30 AM';
    v_office_end_time VARCHAR2(10) := '06:30 PM';
    v_comp_begin_time DATE;
    v_comp_end_time DATE;
    v_days PLS_INTEGER := 0;
    v_hrs NUMBER := 0;
    v_ttltm NUMBER;
    BEGIN
    select trunc(v_end_date) - trunc(v_begin_date)
    into v_days
    from dual;
    select to_date(to_char(sysdate,'DD-MM-YYYY')||' '||to_char(v_begin_date,'HH24:MI'),'DD-MM-YYYY HH24:MI')
    into v_comp_begin_time
    from dual;
    select to_date(to_char(sysdate,'DD-MM-YYYY')||' '||to_char(v_end_date,'HH24:MI'),'DD-MM-YYYY HH24:MI')
    into v_comp_end_time
    from dual;
    select (v_comp_end_time - v_comp_begin_time)/24 into v_hrs from dual;
    IF v_hrs > 4 then
    v_ttltm := v_days + .5;
    ELSE
    v_ttltm := v_days;
    END IF;
    return v_ttltm;
    END;
    As has been noted, this question is best posted on the PL/SQL forum.

  • How to calculate the hour difference between two dates?

    hi all,
    how to calculate the hour difference between two dates?
    eg i trying this...
    ((TO_DATE(TO_CHAR(GRNi.reference_date_4,'hh24:mi'),'hh24:mi') -
    TO_DATE(TO_CHAR(NVL(GRNi.reference_date_3,SYSDATE),'hh24:mi'),'hh24:mi'))*24)*60 Act_Hr
    Reg.
    AAK

    Hi
    To break the diff between 2 dates into days, hours, minutes, sec -- you can use the following:
    select to_char( created, 'dd-mon-yyyy hh24:mi:ss' ),
    trunc( sysdate-created ) "Dy",
    trunc( mod( (sysdate-created)*24, 24 ) ) "Hr",
    trunc( mod( (sysdate-created)*24*60, 60 ) ) "Mi",
    trunc( mod( (sysdate-created)*24*60*60, 60 ) ) "Sec",
    to_char( sysdate, 'dd-mon-yyyy hh24:mi:ss' ),
    sysdate-created "Tdy",
    (sysdate-created)*24 "Thr",
    (sysdate-created)*24*60 "Tmi",
    (sysdate-created)*24*60*60 "Tsec"
    from all_users
    where rownum < 50
    HTH
    RangaReddy

  • To find difference between two dates

    Hi all,
    I am new to this forum and oracle.
    I want to get the difference between two dates. My query is as below...
    sqlserver_utilities.datediff('YY', startdate,enddate)
    I want the difference in year.
    Please help me. It's really urgent.
    Thanks in advance.
    Regards,
    Inam

    Select to_char(enddate,'YY') - to_char(startdate,'YY') fromPLEASE don't do that. There are so many things wrong with it...
    for example:
    1). Why are you subtracting character data types?
    2). What if the start date is 1999 and the end date is 2000? Do you expect to get a difference of -1?
    3). What if the start date is 1 Jan 2000 and the end date is 31 Dec 2000? Do you expect to get 0 instead of 1 or .997?
    4). Why would you convert dates to something else when they are inherently subtractable.
    5). There are obvious points in the OP's "specification" that are vague - the best thing (after telling them to search, of course since this has been answered a million times already) would be to try to clarify the spec.
    John

  • Calculate difference between two dates/times

    Hi all,
    Is there any function module to calculate difference between two dates/times which are in TIMESTAMPL format.
    I need to know how many millisconde(second,minutes, hours... )there is between these two times.
    Please, It is urgent
    Thank you all.
    Karim

    hi,
    try the following function
    CALL FUNCTION 'CCU_TIMESTAMP_DIFFERENCE'        
          EXPORTING                                  
               timestamp1 = timestamp1               
               timestamp2 = timestamp2               
          IMPORTING                                  
               difference = diff                     
          EXCEPTIONS                                 
               OTHERS     = 1. 
    the above function gives the difference in seconds...
    try the following  code to set the resolution to milliseconds..
    SET RUN TIME CLOCK RESOLUTION LOW
    check the thread for details:
    SET RUN TIME CLOCK RESOLUTION?
    all the best!!!
    Regards,
    Aparna

Maybe you are looking for

  • "the operation could not be completed as there is no video"

    Hi. I've been logging and capturing without incident for weeks now, from my JVC BR-DV3000 deck to final cut 5. Device control still works fine, so i know final cut is recognizing the deck, but all of a sudden when I set it to capture i get an error m

  • MacBook Pro Bluetooth problems

    Anyone have any problems with BlueTooth mice and the MacBook Pro? I've got a 2010 17" MacBook Pro running 10.7.1 (but the problem pre-dates Lion). The mouse is "jerky" meaning that when I move the mouse it doesn't follow immediately sometimes, and im

  • F110  - can specify RFFO program for bespoke SAPscript to print out

    Hi SAPer, I am working to figure out how to print out bespoke SAP script while using a Standard RFFO program.  The output is a print out form on paper. I have tried RFFOUS__C and RFFOD__T, so far, but somehow, F110 does not produce any print out at a

  • HELP I DELETED MY IPOD MUSIC AND I DONT KNOW HOW TO GET IT BACK!

    OK SO I WAS TRYING TO PUT THE MUSIC ALREADY ON MY I POD ONTO I TUNES AND INSTEAD MADE A PLAYLIST ON MY IPOD WITH THE MUSIC THAT WAS ALREADY ON IT- I WENT TO DELETE THE PLAYLIST AND IT DELETED ALL THE MUSIC ON MY IPOD HOW DO I GET IT BACK? THANK YOU

  • What is my forms 6i version ?

    Hello, I would like to find out what is my forms 6i version on unix hp machine. What is the command ? Thanks