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;

Similar Messages

  • 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;

  • 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 ...

  • 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 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

  • 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

  • HT5706 My Apple TV is frozen on the time and date setting and then it goes to the screen saver I tried changing the batteries on the remote and it still doesn't make a difference someone help

    My Apple TV is frozen on the time and date setting and then it goes to the screen saver I tried changing the batteries on the remote and it still doesn't make a difference someone help...has anyone else had these problems?

    Hi i ran into the same problem Ithoght it was the control, i changed the batteries the the control, and stil did not work, in the same connection (network and everything) i installed a new one and it worked perfectly, i can deduct the unit is nit working properly

  • 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

  • Delivery date getting calculated wrongly in delivery created via VL10D

    Hi Gurus,
    We have a strange issue, where in delivery date is getting calculated wrongly for replenishment delivery created via VL10D.
    When we are creating via VL10D , delivery date is getting the additional 30 days from MaxDlvCrteDate . With initial investigation i see that VL10D has delivery creation profile 0101 for which no of days maintained in max delv creation date is 30 .
    I assume that the delivery date is getting the additional days from delivery creation profile felid no of max delv creation date .
    I have created the delivery on 24.03.2011, as per the route no of TL time is 9 days , So Ideally the delivery date should be 04.04.2011 , however system has calculated it as 23.04.2011
    Delivery no             No of days in MaxDlvCrteDate                        Delivery  date
    213443158                           30                                                       23.04.2011
    If I create the delivery for the same PO using t-code VL10B, then delivery date is calculating correctly.
    Not sure why system behavior is strange.
    Please help me with your inputs to resolve the issue..
    Thanks in advance

    Please request one Abaper  to solve this problem.
    You cannot due nothing as the problem is in Code.
    Regards
    William

  • How we calculate the date difference between two list in SharePoint 2010

    Hi friend's....I have two list first is list1. In this list i have two coulmn start_date and End_date. In second list2 i have two column HolidayName and Holiday_date. Now i want two find the number of day in list1 Excluding Weekend and Holiday_date(that
    column from list2). How i will do ..? Please help me dosto..

    Thanks for reply...
    I have done the date difference in list1. But i want to Exclude the Holiday_date form list2.
    I have list1 - Start_date , End_date, Number_of_day(Exclude weekend and Holiday_date between Start_date and End_date )
    list2 - HolidayName, Holiday_date
    Now how i will calculate the Number_of_day in first list.

  • Query report with date difference.

    Hi Expert,
    I'm using below query to monitor unreleased checks. we have a policy that the holding period for unreleased check is 5 working days.
    SELECT T2.[CardCode], T2.[CardName], T0.[TransId], T0.[DueDate], T1.[Credit], T1.[U_DisBank], T4.[Name], DateDiff(dd,T0.[DueDate],GetDate()) As 'OverDue Days' FROM OJDT T0  INNER JOIN JDT1 T1 ON T0.TransId = T1.TransId  INNER JOIN OCRD T2 ON T1.ShortName = T2.CardCode  INNER JOIN "@HOFFICE"  T4 ON T1.U_Disbank = T4.Code WHERE T1.[Credit] !=0 AND  T0.[DueDate] >=[%0] AND  T0.[DueDate] <=[%1] AND  T1.[balduedeb]+T1.[balduecred] !=0 ORDER BY T4.[Name]
    However I would like to exclude weekends in computing date difference. Can you please help me modify my query code?
    Thanks,
    Arlmi2000

    Hi,
    A simple solution will be change DateDiff(dd,T0.DueDate,GetDate()) to DateDiff(dd,T0.DueDate,GetDate())*5/7+1
    This can cover all the weekends. If you need to be exact that including public holiday, the coding will be  longer.
    Thanks,
    Gordon

  • Date differences if one of the field not presenting

    Hi All,
    I have two attributes start date and end. I have created formula replacement variable.
    some  times one of the field coming as blank, in such acase system writing some garbage value but i need blank.
    How to resolve this issue.
    Reagrds,
    J B

    Hi,
    You can create a new formula in query designer with a condition such that date difference doesn't fall in the invalid value. If it that invalid value put the result as '0'.
    http://help.sap.com/saphelp_nw04/helpdata/en/23/17f13a2f160f28e10000000a114084/frameset.htm
    If the output is showing as '0' for the invalid values then in the query properties select the Display zeroes as Do Not Display Zeroes.
    http://help.sap.com/saphelp_nw04/helpdata/en/1e/99ea3bd7896f58e10000000a11402f/frameset.htm
    Hope this helps.........
    Rgs,
    Ravikanth.

Maybe you are looking for

  • Can not print shipping labels on FedEx with Firefox 4

    I print shipping labels from FedEx's website using their ship manager online. Now with Firefox 4 I can not get shipping labels to print with any of my printers. I had to use IE to get it to print a label. I spent almost an hour with FedEx tech suppor

  • GS60 2PE Ghost Pro extra power adapter - UK

    Hi, I live in the UK and I would like to buy an additional power adapter for my Ghost Pro. I've called MSI and they don't have any to sell. I've googled the model number of the power adapter (ADP 150VB) but I don't see any for sale in the UK. There a

  • HT201471 mini ipad 32 wifi

    can anyone please help mini ipad won't start just as usb cable pointing to itunes logo on screen,it was working fine

  • Java3D

    i downloaded java3d opengl version and when i try to compile the examples it's give these exceptions -----------------------------------------------java.lang.UnsatisfiedLinkError: no J3D in java.library.path      at java.lang.ClassLoader.loadLibrary(

  • "Class not registered​" Error when running Windows Explorer

    Hi,  I've been having trouble running Windows Explorer + any related programs (Control Panel, Internet Explorer, etc.).  Whenever I try to run such programs, a popup containing the following comes up: C:\Users\<username>\AppData\Roaming\Microsoft\Win