Date difference calculation

Hello Everyone,
We need to calculate a day difference between two days. There is many suggestions about using the following approach:
(date1.getTime() - date2.getTime())/86400000.
This seems to work until we hit a Daylight Savings Time issue and nobody seems to talk about that. When in April, for example, we get 1 hour less then the result of the calculation above will not be the whole number. Well, we can use Math.ceil() function for that. Then, in October, we get 1 hour back so now we have to use Math.floor() function to get the right result.
Does anybody have any idea as to when to use one or another. I was thinking of using modulus division. If the result is not equal to zero then we have to apply one of those functions. The question now is, how to identify which function to apply? Or is there any other, less cumbersome way to properly get day difference between two dates?
Any help will be greatly appreciated.
Thanks,
Yourii

I think i figured out how to calculate the difference in days with Daylight Savings Time changes. Here is the code:
     * This method returns difference in days between two Dates passed in.
     * It identifies Daylight Savings Time changes and automatically
     * adds or substracts one hour when needed ...
     private int dayDifference(java.util.Date date1, java.util.Date date2) {
     final long M_SECS_PER_DAY = 24*60*60*1000;
     final long M_SECS_PER_HOUR = 60*60*1000;
     long days = (date1.getTime() - date2.getTime());     
     if (days%M_SECS_PER_DAY != 0) {
     if ((days + M_SECS_PER_HOUR)%M_SECS_PER_DAY == 0) {
     System.out.println("Adding one hour ...");
     days += M_SECS_PER_HOUR;
     } else {
     System.out.println("Substracting one hour ...");
     days -= M_SECS_PER_HOUR;
     } else {
     System.out.println("No alterations made ...");
     return (int)(days / M_SECS_PER_DAY);
Let me know what you think ...

Similar Messages

  • Date Difference Calculation in BW3.5

    Hi
    We are calculating date differences between 2 dates i.e. Delivery Date - System Date.For System date we used variable exit to derive the value.But when we create CKF on Delivery Date,we necessary have to keep date field in Drilldown(in rows).But reports needs to give Overview while including date field in rows removes the granularity.
    Is thier any other way we can handle this situation.
    Regards
    Praveen

    You have to put ur delivery date in Rows if u r doing the Formula variable with replacement path. There is no option.
    Khaja

  • Date difference calculation - help!

    hey people, i've got the below method, i'm trying to calculate the difference between two dates. the calculation is wrong as it is outputing the wrong duration... can anyone help?
    public int getDuration(Date startDate,Date endDate)
    GregorianCalendar start = new GregorianCalendar();
    start.setTime(startDate);
    GregorianCalendar end = new GregorianCalendar();
    start.setTime(endDate);
    long diff = 0L;
    if(start.getTime().before(end.getTime()) == true)
    diff = end.getTimeInMillis() - start.getTimeInMillis();
    diff = diff/(24*60*60*1000);
    Long L = new Long(diff);
    return L.intValue();
    THanks, Ian

    In the mean time, a couple of stylisitc suggestions:
    if(start.getTime().before(end.getTime()) == true)
    // == true is redundant and cluttersome
    if(start.getTime().before(end.getTime()))
    Long L = new Long(diff);
    return L.intValue();I'd suggest returning a long, rather than an int. If you insist on returning an int, because you're sure that the number of days will never be more than Integer.MAX_VALUE, then add an assertion that its not.
    assert diff <= Integer.MAX_VALUE : diff + " too big";The Long is overkill. If you do have a small enough value, just do return (int)diff;

  • Date Difference Calculation in BSO Cube

    Hello,
    need help with Date Calc
    I have a Dim. Called Inv Date and another Dim. Check Date( which is Time Dim.)
    I will like to do this calculation Inv Date - Check date and store the difference in a Measure member called days outstanding
    This should return how many days difference between both dates.
    will really appriciate if some one could help.
    thkx
    mits
    Edited by: user12527998 on Jan 28, 2010 1:43 PM

    Hi,
    I always find a post by John Booth's a useful guidance when you are wanting to run calculations with dates, have a read at :- Calculations with dates
    If you are using Version 11 you also have a look at the new date functions e.g. @DATEDIFF - http://download.oracle.com/docs/cd/E12825_01/epm.111/esb_techref/calc_datediff.htm
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • Date difference calculation with user input variable

    Hi,
    I have the following requirement in BEx:
    The user inputs a date value and I have to calculate the difference between the date entered by the user with the Due Date in the cube, to determine the number of backlog days. Basically, I need to calculate Past Due in number of days.  I need to display the Amount due for the Time buckets like 1 -10 days, 11 -30 days.
    The report output has to be in the format below:
    Columns:
    1 u2013 10 days Past Due      $100.00
    11 u2013 30 days Past Due    $15.00
    Rows:
    Customer#    
    The cube has data from Jan 2005 to June 2008.
    For Eg:   User Input Date =   04/30/2008.
    It should compare the input date to the due date for each record in the cube.
    Any suggestions are appreciated.

    Hi Kumar,
    We have developed simar reports in our previous projects.
    You need to follow the following steps.
    1. Create a new restricted key figure globally on Past Due $100. Restriction details I will let you know in the ensuing steps.
    2. Create another restricted key figure globally on Past Due $15. Restriction details I will let you know in the ensuing steps.
    3. Create a Z varuable on Calday and offset it -1 (use the button next to exclude button).
    4.Create another Z varuable on Calday and offset it -10 (use the button next to exclude button).
    5. Create another Z varuable on Calday and offset it -11 (use the button next to exclude button).
    6. Create another Z varuable on Calday and offset it -30(use the button next to exclude button).
    7 Restrict the RKF past due 100$ (defined in sl 1)between the variable range defined in 3 and 4.
    8. Restrict the RKF past due 15$ (defined in sl 2) between the variable range defined in 5 and 6
    Now drag and drop those two RKF to column and you will get the desired result in C1 and C2 as follows:
    Columns:
    C1 :1 u2013 10 days Past Due $100.00
    C2 :11 u2013 30 days Past Due $15.00
    If the above info serves your purpose, please reward me with the point.
    Regards,
    Subha

  • Date Difference Calculation problem

    I am creating a form which should calculate the number of days between two calender dat
    es using the Date2Sum expression but my result cell gives me
    zeo despite setting the locale and the calculation correcttly. Where could
    my problem be?
    Darlington Sakwa

    Validate the date patterns on the date fields match the date patterns used in Date2Num. For example, the attached has a start date with the display date pattern date{YYYY-MM-DD} and that matches the date pattern in my Date2Num function call.
    // form1.page1.startDateNum::calculate - (FormCalc, client)
    if (form1.page1.startDate.isNull) then
      $.rawValue = ""
    else
      $.rawValue = Date2Num(form1.page1.startDate.rawValue,"YYYY-MM-DD")
    endif
    Steve

  • Date difference calculation help needed

    Hi,
    I have a form with a date field and one text field which is hidden..in case the date field value is less than the current date minus 3 years then the text field should display else not. Please advice what logic/code can be used.
    Any suggestions would be highly appreciated !!
    Thanks
    Kapil

    In the mean time, a couple of stylisitc suggestions:
    if(start.getTime().before(end.getTime()) == true)
    // == true is redundant and cluttersome
    if(start.getTime().before(end.getTime()))
    Long L = new Long(diff);
    return L.intValue();I'd suggest returning a long, rather than an int. If you insist on returning an int, because you're sure that the number of days will never be more than Integer.MAX_VALUE, then add an assertion that its not.
    assert diff <= Integer.MAX_VALUE : diff + " too big";The Long is overkill. If you do have a small enough value, just do return (int)diff;

  • Xcelsius doesn't display the date difference in Preview

    Hi,
    Im using the Xcelsius Enterprise 2008 and I use XML connectivity for the source. I would like to do some date difference calculation on my spread sheet. But the result of the date difference does no appear on the Preview for some reason. My XML file has got the date format dd/mm/yyyy hh:mm. I tried to convert the date to number format by multiplying the date by 1. When I do this the result appears correctly as I want on the Preview, but the problem is when there is a first refresh, the date difference shows a error value "#Value". I tried to enable XML Map Properties -> When refreshing or importing data:
    1. Overwrite existing data with new data
    2. Append new data to existing XML lists.
    But still not of any use. Could any one please give me a tip to resolve my problem.
    Many thanks in advance.
    Priya

    Hi Priya
    Can you please tell me what formula are you using to take difference in dates?
    Just to tell you as a point of information, Xcelsius is capable to handle very limited set of formulas. In spreadsheet you will see the formula working perfectly fine but right after hitting preview button you wont be able to see values calculated by certain formulas in Excel. So, its always good to use less and very basic formulas.
    Regards,
    Waqas

  • Date difference based on the conditions is giving wrong values

    Hi,
    In creating the formula for conditional date difference calculation,
    i.e.,
    if (sto date is 0) then (act date - mat rel date) else (sto date is not equal to 0) then (sto date - mat rel date)
    So I tried with,
    (sto date == 0) * (act date - mat rel date) + (sto date <> 0) * (sto date - mat rel date)
    But I am getting a wrong value even with decimals as days can't be in decimals. Please suggest where I am going wrong in calculation.
    Thanks,
    Best Regards,
    Darshan MS

    Hi Darshan,
    First of all, were the dates converted already to keyfigure?
    If not, please check:
    Convert a Characteristic into a Key Figure (BEx)
    If they were already converted, try this:
    (sto date == 0) * (act date - mat rel date) + (sto date - mat rel date)
    Regards,
    Loed

  • Date duration calculation in the BLS

    All,
    We are using MII 12.0.6
    I am looking at a very peculiar behavior while calcualting the date difference between 2 dates.
    For ex. the following expression: 
    (datediffminutes(datetoxmlformat("2010-3-21 14:06:30 ", "yyyy-MM-dd hh:mm:ss"), datetoxmlformat("2010-05-24 08:14:54","yyyy-MM-dd hh:mm:ss")))/60
    yields 1530.13 as the result(this is the correct evaluation) when tested from within the Link editor (clicking the evaluate button).
    Now saving this transaction and giving the value of the above expression to an output param followed by calling this trx from an Xacute query yields 1529.13 as the result (I hr difference than above).
    I have tested this with a few more dates going as far back as Dec 2009 yielding the same one hour difference.
    On the other hand for any start date in May 2010 yields a correct result even when called from an Xacute query.
    I tested this  in a 12.0.2 system and found this behavior absent as in all was working as expected.
    Has anyone come accross this before?Do you know if the latest patch has this fixed?
    Just to cross check can anyone giive this a try in their 12.0.6 or higher system and report back?
    Thanks a lot for your help.
    Kind Regards
    Udayan

    Hi Udayan,
    Please open a ticket.  It sounds like a bug, although a few years back there was a problem with one of the java packages and Daylight Savings Time.  If you search this forum for all time, you will find some of the postings. 
    Since there have been changes to when Daylight Savings Time start and ends, it is likely related and could possibly be java related instead of MII.  I doubt it, but it is possible. 
    Edit:
    A little more research turned up differences in how Daylight Savings Time is calculated in different countries/continents.  Coincidentally, the US started on March 14th this year while the European Union started on March 28th (this date sounds familiar).  Not sure what timezone, you are in, but you may want to play around with the timezone settings for your computer to see if the error is consistent with US vs European timezones (or wherever you happen to be located).
    [Daylight Savings Times around the world|http://www.worldtimezone.org/]
    Thanks,
    Mike
    Edited by: Michael Appleby on May 25, 2010 12:41 PM

  • Date Based Calculations

    We have the following requirements:
    1.     In terms of minutes provide the difference between the expected time and actual time of arrival
    2.     With a tolerance level of 5 minutes compare expected and actual time dates providing an On time value
    Are these date based calculations straight forward as part of the data model (not at query level) in BW and if so how is this done?  Thanks
    We will create Key Figure DAT InfoObjects

    Thanks for that.  I have had a look at the FM and the input values are:
    Date 1
    Time 1
    Date 2
    Time 2
    I am aware that I can get say right set of numbers.  However is the time part stored in BW?
    Thanks very much guys have checked.  Oscar TIMS is available in BW.  Have awarded points
    Message was edited by:
            Niten Shah

  • Max - min date difference

    Hello Guys, how are you.
    I'm facing a problem whan I try to get the difference between the max and min date of a KF.
    Mi requirement is like this:
    Min Date Max Date Difference (max - min)
    20/06/2008 26/06/2008 6
    My query result is like this:
    min date max date difference
    20/06/2008 26/06/2008 0
    It seems like the formula for getting the difference between the other 2 formulas is not working, because I'm using the function of aggregattion, based on some characteristic, in order to have the max value of the date in one formula, and then have the min value of the date in other formula (the KF store for date is the same, that's the reason i have to use aggregation in order to calculate min and max value).
    Then I have a third formula to calculate the difference between the min value and the max value, but it seems that its not working because of the aggregation.
    Can you please give me some ideas of how can i obtain the desire result.
    THANKS IN ADVANCE

    Hi Carmonia,
    (a) If you want to perform calculations on DATE and if both dates are characteristic infobjects, then you can go for Formula Replacement Path.
       1. Create a New Formula or CKF and then select a Formula Variable. Right click and select New Varaible.
       2. Now create a Variable for one of the Characteristic of Date type with  processing type Formula - Replacement path. Select Replace with 'Key' and Dimension as 'Date'. Similarly create another formula replacement variable for another characteristic.
       3. Now you can taken both these variables in calculations(such as A-B).
    (b) If you are using key figure for the dates, then try by using DATE function in Data Functions of New Formula.
    Example: DATE(kfig_MaxDate)-DATE(kfig_MinDate). Also try DATE(kfig1_MaxDate-kfig2_MaxDate).
    ***Assign points if useful.
    Thanks,
    Sasi

  • Row wise Date Difference

    Hi
    I have one column which contains Date field. and I want date difference between two rows like (1st row- 2nd row),(2st row- 3nd row) 3-4,4-5 like that.
    How I can get this
    Thanks
    Siddhartha P

    As for the minutes calculation it doesn't take Einstein to know that the number of minutes in a day = 24 (hours) * 60 (minutes)
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 1 as id, sysdate-10 as dt from dual union all
      2             select 2, sysdate-7.4 from dual union all
      3             select 3, sysdate-6.45 from dual union all
      4             select 4, sysdate-2.82 from dual union all
      5             select 5, sysdate from dual)
      6  -- END OF TEST DATA
      7  select id
      8        ,dt
      9        ,dt-lag(dt) over (order by id) as dt_diff_days
    10        ,(dt-lag(dt) over (order by id))*(24*60) as dt_diff_minutes
    11* from t
    SQL> /
            ID DT                  DT_DIFF_DAYS DT_DIFF_MINUTES
             1 30/11/2007 13:07:37
             2 03/12/2007 03:31:37          2.6            3744
             3 04/12/2007 02:19:37          .95            1368
             4 07/12/2007 17:26:49         3.63          5227.2
             5 10/12/2007 13:07:37         2.82          4060.8
    SQL>

  • Date difference problem.....

    Hi,
    I am calculating the date difference with the Formula variables.
    My requirement is to find the rocords, where date difference is 0.
    , Means same date.
    But I am facing one problem while testing the query.
    If for the two date , if both the columns are not having any value,
    it contains # , and if I calculate the diffence of this,
    This is also coming as 0 in the Date difference column.
    Can somebody let me know how to rectify/avoid this situation?
    Thanks , Jeetu

    Hi Jeetu,
    According to your requirement, if record is there, there should be at leaset one date value say "Starting Date".
    If "ending date" value is blank, the formula returns a junk/garbage value.
    If both the date values are available, the formula returns the number of days corectly.
    But, both the date values are blank, there should not be any record in such case. If you see this case in your data base,
    that can be either wrong data record or you need to exclude such condition from your query.
    Thanks,
    Kiran.

  • Date Difference in OBIEE

    Hi
    I have two date columns and I want one logical column which contains difference of those two DATE columns.
    But I found that we dont have any Date difference or Date Add functions in OBIEE Answers.
    Can anyone tell me any work around for the Date ADD/DIFF functions?
    Thanks
    Radha

    Or if you want database specific date functions, use EVALUATE and then specify the database functions. Check my blog entry here http://oraclebizint.wordpress.com/2007/09/10/oracle-bi-ee-10133-support-for-native-database-functions-and-aggregates/
    Thanks,
    Venkat
    http://oraclebizint.wordpress.com

Maybe you are looking for

  • Web Template is not able to fetch data from Data Provider

    hi friends,            i have created a reporting agent for a particular query and given all the necessary parameters, defined the variants and activated this and created a scheduling package to this ,assigned my query to the scheduling package      

  • Missing one of external HD partitions

    I have a 160Gb external drive with two partitions- a backup and an archive. Every year I archive the photos, movies, and music files from that year, so I have thousands of files in the archive. This evening I was trying to open some old pictures from

  • Skype crashing my computer while joining calls

    everytime i try to join a call on my computer freezes but i can still hear the people in the call and i have to shut down my computer manually by holding the power button

  • Event case missing mouse events on active-x component

    I am using a Treeview and capturing selections in the tree using mouse events (event structure). I have a problem where approx 3 out of 15 mouse events are not actioned by the event structure - has anyone else had this problem or is there any suggest

  • How to remove plugin container in firefox 14.0.1?

    Is there a way to remove plugin-container in firefox 14.0.1? Any extra process is unacceptable and I've always had plugin-container remove before. But from what I read it is needed to run the newest flash, so can gives us a option to automatically cl