Date Arithmetic: Remainder vs. Modulus

I am working on formating a report of overdue items. One of the requirements is to list the elapsed time between the due date and the current date, expressed in terms of years and days. I have ran across some curious findings in the results from the REMAINDER function which has led me to use the MOD function instead. Consider the following:
DECLARE
d1 DATE;
d2 DATE;
d3 DATE;
years NUMBER(38,12);
years2 NUMBER(38,12);
v_raw NUMBER(38,12);
v_raw2 NUMBER(38,12);
v_remainder NUMBER(38,12);
v_mod NUMBER(38,12);
v_mod2 NUMBER(38,12);
v_rem2 NUMBER(38,12);
BEGIN
d1 := to_date( '09-JUL-2007', 'DD-MON-YYYY' );--SYSDATE;
d2 := to_date( '24-JUL-1995', 'DD-MON-YYYY' );
d3 := to_date( '24-JUN-1995', 'DD-MON-YYYY' );
years := TRUNC( ( d1 - d2 )/365 );
years2 := TRUNC( ( d1 - d2 )/365 );
v_raw := d1 - d2;
v_raw2 := d1 - d2;
v_remainder := TRUNC( REMAINDER( d1 - d2, 365) );
v_rem2 := TRUNC( REMAINDER( d1 - d3, 365) );
v_mod := TRUNC( MOD( d1 - d2, 365 ) );
v_mod2 := TRUNC( MOD( d1 - d3, 365 ) );
dbms_output.put_line( 'D1 is '||to_char( d1, 'DD-MON-YYYY' )||'.');
dbms_output.put_line( 'D2 is '||to_char( d2, 'DD-MON-YYYY' )||'.');
dbms_output.put_line( 'D3 is '||to_char( d3, 'DD-MON-YYYY' )||'.');
dbms_output.put_line( 'Raw difference between d1 and d2 is '||v_raw||'.');
dbms_output.put_line( 'Number whole years difference between d1 and d2 is '||years||'.');
dbms_output.put_line( 'Number whole days difference, using the remainder function, between d1 and d2 is '||v_remainder||'.');
dbms_output.put_line( 'Number whole days difference, using the modulus function, between d1 and d2 is '||v_mod||'.');
dbms_output.put_line( 'Raw difference between d1 and d3 is '||v_raw2||'.');
dbms_output.put_line( 'Number whole years difference between d1 and d3 is '||years2||'.');
dbms_output.put_line( 'Number whole days difference, using the remainder function, between d1 and d3 is '||v_rem2||'.');
dbms_output.put_line( 'Number whole days difference, using the modulus function, between d1 and d3 is '||v_mod2||'.');
END;
The code above produces the following output:
D1 is 09-JUL-2007.
D2 is 24-JUL-1995.
D3 is 24-JUN-1995.
Raw difference between d1 and d2 is 4368.
Number whole years difference between d1 and d2 is 11.
Number whole days difference, using the remainder function, between d1 and d2 is -12.
Number whole days difference, using the modulus function, between d1 and d2 is 353.
Raw difference between d1 and d3 is 4368.
Number whole years difference between d1 and d3 is 11.
Number whole days difference, using the remainder function, between d1 and d3 is 18.
Number whole days difference, using the modulus function, between d1 and d3 is 18.
D1 represents the current date (SYSDATE was not used to preserve consistency in the results). Although D1 is greater than both D2 and D3, the REMAINDER function is somehow producing a negative result for D2 (D3 calculations come out fine). I would not have expected that a negative result is possible since D2 occurs almost 12 years prior to D1!
It appears that, for some reason, REMAINDER is converting the dates to the Julian dates (day of the year) and somehow ignores the year for the calculations. This is clearly incorrect. I could not find any reference to this anomaly in the SQL reference; I am uncertain whether this is a known issue.
Your insight would be appreciated. Thanks in advance.

...except that the REMAINDER function is mathematically incorrect!
The division algorithm states that given two integers a and d, with d ≠ 0 there exist unique integers q and r such that a = qd + r and 0 ≤ r < | d |, where | d | denotes the absolute value of d. Using the numbers from my example, the formula becomes:
4368 = ( 11*365 ) + r
If you apply the remainder from the MOD example (353), the formula holds true. If you apply the remainder from the REMAINDER function example (-12), the numbers do not add up.
Hence, by using the ROUND function on the quotient, the REMAINDER function has the ability to produce invalid results.

Similar Messages

  • Date arithmetic...have ur points..

    Hi all,
    I want to do arithmetic operations on date type fields..
    like i want to add 5 days to current date...like this..
    Pleas help me...
    & have ur points..
    Regards,
    pradeep

    Hi Pradeep...
    Find some of the useful date operations here.
    Data : v_date1 like sy-datum.
    Data : v_date2 like sy-datum.
    Data : v_diff type i.
    **Assigning date variables
    v_date1 = sy-datum.
    v_date2  = sy-datum.
    **Extract the individual parts of date
    v_date1+6(2) = '01' .       "set the Day as the First day of the month
    write:/ v_date1.
    **Adding no of days.
    v_date2 = v_date2 + 5.
    write: v_date2.
    **Subtracting two date fields
    v_diff  = v_date2 - v_date1.
    write:/ v_diff.
    Additionally you can find various FMs to process dates.
    Some of them can be found in Function group SCAL.
    <b>REWARD POINTS IF HELPFUL.</b>

  • How to get the number of minutes or hours from date arithmetic ?

    Thanks in advance,
    I have two date fields that I would like to derive the number of minutes or hours via the following:
    select start_date - end_date from dual;
    How do I get HH:MM results ? Thanks

    If greater than 24 hours you'll need to calculate the hours and minutes as numbers individually. (You can then display them in whatever format you choose)
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select to_date('6-10-2008 08:00','DD-MM-YYYY HH24:MI') as from_dt, to_date('7-10-2008 12:30','DD-MM-YYYY HH24:MI') as to_dt from dual)
      2  --
      3  select from_dt, to_dt, to_dt-from_dt
      4        ,to_char(trunc(sysdate)+(to_dt-from_dt),'HH24:MI') as hrs_mins
      5        ,trunc((to_dt-from_dt)*24) as hrs
      6        ,trunc((((to_dt-from_dt)*24)-trunc((to_dt-from_dt)*24))*60) as mins
      7* from t
    SQL> /
    FROM_DT           TO_DT             TO_DT-FROM_DT HRS_M        HRS       MINS
    06-OCT-2008 08:00 07-OCT-2008 12:30        1.1875 04:30         28         30
    SQL>

  • Date arithmetic

    has anyone used this code before:
    SELECT {fn TIMESTAMPDIFF (SQL_TSI_DAY, {fn CURDATE()}, '1998-12-09')} FROM DUAL;
    i'm getting invalid character when i run it from sqlplus. do i need to run a package to recognize the function or did i miss something. thanks for all the help.
    if you haven't used this one is there a way to calculate two dates and figure out the difference in hours not days. i'm using sysdate and a string of dates which needs to be converted.
    null

    don't put your questions on multiple forums, thinking that others are idiots to answer.

  • Date Arithmetic Bug(s) with Oracle?

    Post Author: Andrew Reedick
    CA Forum: Data Connectivity and SQL
    The following sql returns a value of 60 from run via sqlplus:
    select to_date('14-Dec-2007')-to_date('15-Oct-2007') as foo from dual
    However, when CR runs it, it returns a value of -304.
    Needless to say, I would prefer that the value be the number of days between the two dates, which is 60.  Anyone have any idea as to why CR is screwing up?
    Great.  Another discrepancy:
    The following
    select sysdate + (to_date('14-Dec-07')-to_date('15-Oct-07')) as foo from dual
    returns a value of 25-JAN-08 using Oracle sqlplus, whereas CR returns 1/26/2007.  Any idea why the two would return different date values when using the same sql?
    Is there something wrong with CR's Oracle db driver?
    (SYSDATE is 1/26/07)

    Post Author: Andrew Reedick
    CA Forum: Data Connectivity and SQL
    Looks like CR's Oracle driver and sqlplus are using different defaults for the dates.
    Explicitly specifying the date format seems to have fixed the problem.  Ex:
    (to_date('2007-12-14', 'yyyy-mm-dd')-to_date('2007-10-15', 'yyyy-mm-dd'))

  • Split with date arithmetic

    Hi,
    I have the following input [test 01-Jan-10 14] and wanted to split the text so that I would get 01-Jan-10 + 14 days? Is this possible using sql?
    Thanks!
    Edited by: user11922215 on Aug 16, 2010 3:23 PM

    if the format is always same and if data is never bad and is always identical, then it can be
    SQL> WITH t AS
      2       (SELECT 'test 01-Jan-10 14' dt
      3          FROM DUAL)
      4  --
      5  SELECT   TO_DATE(SUBSTR(dt, INSTR(dt, ' '), 10), 'dd-mon-yy')
      6         + TRIM(SUBSTR(dt, INSTR(dt, ' ', 1, 2))) dt
      7    FROM t;
    DT
    15-JAN-10and even you hard code as the other user mentioned after my post
    SELECT   TO_DATE(SUBSTR(dt, 6, 10), 'dd-mon-yy')
           + SUBSTR(dt, 16) dtEdited by: Clearance 6`- 8`` on Aug 16, 2010 6:45 PM

  • DATE arithmetic in SQL Workshop v SQL Developer - different results

    Hi
    I want a date picker to default to the Monday of the current week. I'm basing it on TO_CHAR with a format mask so this should give me the number of the day of the week:
    SELECT SYSDATE, to_char(SYSDATE, 'D')
    FROM dual
    In APEX SQL Workshop, I get
    09/25/2013  4
    which is wrong - today is Wednesday.
    The same code in SQL Developer gives
    25-SEP-13  3
    which is correct.
    Am I missing some APEX setting here which determines when the start of the week is (Monday v Sunday)?
    Many thanks
    Brian
    Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 - 64bit Production
    APEX 4.2.2.00.11
    Windows 2008 R2 Enterprise Server

    I'm guessing this: (from Oracle documentation)
    The datetime format element D returns the number of the day of the week (1-7). The day of the week that is numbered 1 is specified implicitly by the initialization parameter NLS_TERRITORY.
    For me:
    select sysdate, to_char(sysdate,'D'), to_char(sysdate,'Day')  from dual;
    25-SEP-13    4    Wednesday
    Which is (for me) correct. (Sunday == 1 )
    What have we learned?
    NLS_TERRITORY can be different depending on who/how/when the DB connection is made.
    This is the same as NLS_DATE_FORMAT.
    Solution:
    Never ever trust anything that depends on them unless the code explicitly sets the value.
    This is why you ALWAYS provide the date format when converting from String to Date using the TO_CHAR();
    MK

  • Unsupported date arithmetic exception.

    hi there,
    I am trying to open a workbook from the database and i am getting the exception as
    "Some of your workbooks may be deleted by an administrator"..
    Is there any mechanism to retrieve the failed/corrupted workbooks from the database..
    Please help me..
    Its very very urgent..
    Thanks
    Divya.

    Divya.
    I'm starting to get a bit confused here. In another thread you mentioned that you were getting an error condition for an arithmetic operation.
    Now you're saying that it might be 'deleted by an administrator'?
    - Is this the same workbook?
    - 2 differernt errors or the same?
    - Deleted by an administrator - that's a new one for me - tell him/her not to delete the darn thing then!
    - As I mentioned in the other thread, although maybe someone else knows, I know of no mechanism to retrieve a failed / corrupted workbook and can only suggest what I said in the other thread - try and fudge what you need in the EUL at the folder / item level, just to get the workbook to open, so you can fix it there.

  • Simple date arithmetic

    I need to subtract date1 from date2 and show the result in HH:MI:SS format. Thanks in advance for the help and the effort.

    SQL> with t as (select sysdate - 2.254656334 as date1, sysdate as date2 from dual),
      2       t2 as (select numtodsinterval(date2 - date1,'DAY') int from t)
      3       select    int,
      4                 extract(DAY from int)*24+
      5                 extract(HOUR from int)||' hour(s) :'||
      6                 extract(MINUTE from int)||' minute(s) :'||
      7                 extract(SECOND from int)||'second(s)' diff
      8    from t2
      9  /
    INT                 DIFF
    +000000002 06:06:42 54 hour(s) :6 minute(s) :42second(s)
    SQL>

  • How to get Public Key Remainder?

    Hi Friends..
    Sorry, i have a little doubt regarding the Public Key Remainder..
    What is Public Key Remainder used for?.. is it a part of Public Key?.. How to get it from Public Key, especially in Java?
    As far as i know that the Public Key is constructed with Modulus and Exponent, and with this we can Encrypt and Verify data was signed by Private Key..
    In Java, we can expose Public Key's modulus and public exponent using RSAPublicKey, there's no method to expose Public Key's Remainder..
    Please help me regarding this..
    Thanks

    Leonardo Carreira wrote:
    Hi Shane,
    Thanks for your reply.. :)
    safarmer wrote:
    In that case the exponent and remainder are you public key (exponent and modulus) and the certificate is defined in the definitions section of Book 3. It is a secure way of verifying the public key and it's owner through a trusted certification authority.
    EMV Book 3 tends to use Remainder and Modulus interchangeably.You mean, the Issuer (in this case one of E,M, and V) should provide 2 certificates for 1 card?..
    This is implemented on SDA or DDA?..
    Sorry, i'm still have no idea..
    The Remainder and Modulus should be used interchangeably?..
    How the Host and Card can decides in each transaction whether it will use Remainder or Modulus?..I mean that the terminology is used interchangeably. They refer to the same thing as far as the actual key is concerned.
    Cheers,
    Shane

  • Can some one help me with this date stuff

    Hello,
    I wat to write a method that will take a date or a month and then return the time period
    b4 that date or month..criteria would be like this..
    if the pweriod is weekly then the enddate will be passed and it should return date that was 7 days
    prior to the enddate. For e.g
    enddate = 3 April 2002
    the method should return
    begindate = 27 March 2002
    here is the method I am trying to work with...
    what I am doing do far is a break down the date into integer values and then reconstruct the date again
    ...I am not being successful doing so..please take a look at my code and tell me what am I doing wrong
    thanks
    public static Date getBiginingOfPeriodDate(Date endDate){
    Date beginDate = null;
    Calendar calendar = Calendar.getInstance();
    System.out.println("Date passed = "+endDate);
    calendar.setTime(endDate);
    int iDay = calendar.get(Calendar.DAY_OF_MONTH);
    int iMon = calendar.get(Calendar.MONTH);
    int iYr = calendar.get(Calendar.YEAR);
    System.out.println("End date int values [ "+iDay+", "+iMon+", "+iYr);
    calendar.set(iDay,iMon,iYr);
    System.out.println("create end date from in values [ "+calendar.getTime()+" ]");
    return beginDate;
    }

    If all you want to do is simple date arithmetic, such as subtracting 7 days from a date, just use the java.util.Calendar class, which provides methods (such as add) to do that for you. Don't "reinvent the wheel".

  • How to make a report to display next 18 months of data with when user select a particular month from the filter in power pivot tabular model.

    Hi,
    i have a  dimension table  with month_key having values (201201,201202,201203.......202011,202012) and month name ( Jan 12, feb 12,......NOV 20, Dec 20)  and a fact  table with columns (month_key ,measure_types, Amount)
    My requirement is to create a power pivot report  in which when a user select a month from the filter, the report should display the (selected month+18 ) month's data against each type . when JAN 12 is selected ,the jan 2012 +18 = june 2013
    , month name should be populated with months till june 2013 only .
    i tried creating calculated column"END DATE " in the fact table with  dax expression to calculate the 18th monh from the current month  as below 
    month_key END DATE
    201201       201306    
    201202       201307      
    and thought of filtering the table with month key <= ENDDATE but it is not working as expected. could you please guide me on this ? Is there any time intelligence function that serve the purpose . Iam using  excel 2010
    ..hence could not do any calculation on the report side also. please suggest .
    Thanks in advance                                                                                                                                               

    Do you need to show the measure calculated for those 18 months as a total on 1 row, or do you need to select a single month and then display on row filters 18 distinct rows?
    The first is trivial as driezl has suggested.
    The second will require a second calendar table.
    I created this example workbook for a coworker who had a similar problem. You will have to use the disconnected table as your filter and pull your related table onto the rows.
    Finally, the easiest way to deal with the sort of date arithmetic you need to do is to restructure your date table to have a series of "Sequential" fields. These fields should be the number of units of time since the beginning of your calendar.
    For example, consider a calendar starting on January 1, 2010. For January - December 2010, [MonthSequential] = 1, 2, ..., 12. For January - December 2011, [MonthSequential] = 13, 14, ..., 24, and so on, incrementing by 1 for each sequential month in time.
    Assuming you have this set up in your date tables (one related to your model - DimDate - and one disconnected - DisconDimDate) your measure would look like this:
    18 Month Measure:=
    CALCULATE( [Measure]
    , FILTER( DimDate
    , DimDate[MonthSequential] >= MAX( DisconDimDate[MonthSequential] )
    && DimDate[MonthSequential] <= MAX( DisconDimDate[MonthSequential] ) + 18
    Please review this example along with the workbook I have linked above.

  • I made a new Date object

    See, here's the thing with dates in java, the way i see it. We used to have Date, but Date wasn't international so we got Calendar. But some things, like SimpleDateFormat, still expect java.util.Date. java.sql.Date is out there somewhere, too. None of them have direct support for date differences (i.e. dateA - dateB = 8 days, or whatever). Now you're probably reading this thinking "Java supports all of this" and you're right. Calendar has a getTime method that returns a Date, and i can just pass THAT to SimpleDateFormat. With a little math, getTimeInMillis can be used to find the difference in two Calendars. But i got to thinking, "There should only be one Date object i need to think about," and since i don't ever have enough to do at work i put one together. I don't know if any of you are going to care enough to use it, mostly i'm just looking for advice on features i should add to it, inefficiencies in the design, stuff that's hard to understand, or whatever.
    This is it:
    *This catastrophe brought to you by SrA Meyerin.
    *Proximo Satis pro administatio.
    package awesomedate;
    //The following are imported for the toFormattedString(), toUtilDate(), toSQLDate, and toCalendar() methods, respectively.
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.sql.*;
    import java.util.TimeZone;
    *This class is designed to be the ultimate date object. It stores dates accurate to the millisecond, has the ability to do date
    *arithmetic (adding/subtracting days/months/whatever), date comparison, and date formatting. Also it can, at will, be used as any
    *of the other date objects in the standard java API.
    public class AwesomeDate
         *Milliseconds from the epoch. This field is where everything starts.
        private long millis;
         * The current year. This is the only aspect of the current date that is stored in addition to the milliseconds. Everything else
         * is calculated as needed.
        private int year;
        //The following six variables are fairly self explanatory. I'll explain them anyway.
         *Milliseconds in one non-leap year. This can be passed to the "adjustDate()" method
         * but mostly it is used to make my code more readable.
        public final static long MILLIS_IN_YEAR = 31536000000L;
         *Milliseconds in one leap year. This can be passed to the "adjustDate()" method
         * but mostly it is used to make my code more readable.
        public static final long MILLIS_IN_LEAP_YEAR = 31622400000L;
         *Milliseconds in one day. This can be passed to the "adjustDate()" method
         * but mostly it is used to make my code more readable.
        public static final long MILLIS_IN_DAY = 86400000;
         *Milliseconds in one hour. This can be passed to the "adjustDate()" method
         * but mostly it is used to make my code more readable.
        public static final long MILLIS_IN_HOUR = 3600000;
         *Milliseconds in one minute. This can be passed to the "adjustDate()" method
         * but mostly it is used to make my code more readable.
        public static final long MILLIS_IN_MINUTE = 60000;
         *Milliseconds in one second. This can be passed to the "adjustDate()" method
         * but mostly it is used to make my code more readable.
        public static final long MILLIS_IN_SECOND = 1000;
         *The number of days in each month.
        private int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
         *The timezone offset. GMT is 0, and the default, however, CST (where i live), is -6.
        private int timeZoneOffset = -6;
         *As the name would indicate, this is the number of milliseconds beyond 00:00 of jan 1 of the current year.
        private long millisAfterYear;
         *Basic constructor. Defaults to the current date and time. Works on Greenwich Mean Time, so it may seem off. To avoid this, multiply
         *add your time zone offset * MILLIS_IN_HOUR to the time in milliseconds.
        public AwesomeDate()
            setTimeInMillis(System.currentTimeMillis());
         *Fairly simple constructor. Sets time to the the number of milliseconds passed past the epoch.
        public AwesomeDate(long millis)
            setTimeInMillis(millis);
         *This constructor sets the date to the year/month/day passed.
        public AwesomeDate(int year, int month, int day)
            setDate(year, month, day);
         *This constructor sets the date time to the year/month/day/minute/hour/second passed.
        public AwesomeDate(int year, int month, int day, int hour, int minute, int second)
            setDate(year, month, day, hour, minute, second);
         *When you have the number of milliseconds, the first thing you must calculate is year. Because the number of milliseconds in a
         *year may vary, this is also the most difficult to calculate. This is the method that does it, though.
        private void setYearAfter1970()
            //I don't want to alter the actual number of milliseconds, so i make this variable and perform calculations on it.
            long theseMillis = this.millis;
            //Start at 1970 (the epoch) and work from there.
            year = 1970;
            long nextYear = MILLIS_IN_YEAR;
            //In this loop i subtract the number of millis in whatever year. The condition is if i have enough millis to make it through
                //another year.
            while (theseMillis >= nextYear)
                if (isLeapYear(year))
                    theseMillis = theseMillis - MILLIS_IN_LEAP_YEAR;
                    nextYear = MILLIS_IN_YEAR;
                else
                    theseMillis = theseMillis - MILLIS_IN_YEAR;
                    if (isLeapYear(year + 1))
                        nextYear = MILLIS_IN_LEAP_YEAR;
                year++;
            millisAfterYear = theseMillis;
            this.year = year;
         *Calculating the year from before 1970 must be done differently. It's pretty much just inverted.
        private void setYearBefore1970()
            long theseMillis = this.millis;
            year = 1970;
            long nextYear = MILLIS_IN_YEAR;
            while (theseMillis <= 0)
                if (isLeapYear(year))
                    theseMillis = theseMillis + MILLIS_IN_LEAP_YEAR;
                    nextYear = MILLIS_IN_YEAR;
                else
                    theseMillis = theseMillis + MILLIS_IN_YEAR;
                    if (isLeapYear(year - 1))
                        nextYear = MILLIS_IN_LEAP_YEAR;
                year--;
            millisAfterYear = theseMillis * -1;
            this.year = year;
         *Just what it sounds like. Pass it the number of milliseconds past the epoch and it will calculate the date based on that.
        public void setTimeInMillis(long millis)
            this.millis = millis;
            if (millis >= 0)
                setYearAfter1970();
            else
                setYearBefore1970();
         *Returns the number of milliseconds from the epoch.
        public long getTimeInMillis()
            return this.millis;
         *Returns the current year.
        public int getYear()
            return this.year;
         *Sets the date to 00:00 of Jan 1 of the passed year.
        public void setYear(int year)
            this.year = year;
            long theseMillis = 0;
            if (year > 1970)
                //Kind of like setYearAfter1970 method, except it's adding instead of subtracting. So actually it's the opposite.
                for (int cntr = 1970; cntr < this.year; cntr++)
                    if (isLeapYear(cntr))
                        theseMillis = theseMillis + MILLIS_IN_LEAP_YEAR;
                    else
                        theseMillis = theseMillis + MILLIS_IN_YEAR;
            else
                for (int cntr = 1970; cntr > this.year; cntr--)
                    if (isLeapYear(cntr))
                        theseMillis = theseMillis - MILLIS_IN_LEAP_YEAR;
                    else
                        theseMillis = theseMillis - MILLIS_IN_YEAR;
            //On a leap year there are 29 days in February. If not, there's 28.
            if (isLeapYear(year))
                daysInMonth[1] = 29;
            else
                daysInMonth[1] = 28;
            //This variable helps me calculate denominations of time that are below year.
            millisAfterYear = 0;
            setTimeInMillis(theseMillis);
         *Sets the month to the one that you passed, 0 being January and 11 being December.
        public void setMonth(int month)
            if (month < 0 || month > 11)
                throw new ArrayIndexOutOfBoundsException(month);
            long theseMillis = getTimeInMillis();
            int days = 0;
            setYear(this.year);
            if (getTimeInMillis() > 0)
                theseMillis = theseMillis - getTimeInMillis();
            else
                theseMillis = theseMillis + getTimeInMillis();
            for (int cntr = 0; cntr < month; cntr++)
                days = days + daysInMonth[cntr];
            millisAfterYear = days * MILLIS_IN_DAY + 1;
            setTimeInMillis(getTimeInMillis() + millisAfterYear);
         *Returns the month stored in this object. With this object 0 represents January and 11 represents December.
        public int getMonth()
            long theseMillis = millisAfterYear;
            int cntr = 0;
            while (theseMillis > (MILLIS_IN_DAY * daysInMonth[cntr]))
                theseMillis = theseMillis - MILLIS_IN_DAY * daysInMonth[cntr];
                cntr++;
            return cntr;
         *Set the day of month to the one passed.
        public void setDayOfMonth(int day)
            if (day < 1 || day > daysInMonth[getMonth()])
                throw new ArrayIndexOutOfBoundsException(day);
            setMonth(getMonth());
            //Internally, this actually works starting at zero, however to anyone using this class it appears to start at 1. Therefore
                //i must subtract one here.
            long addMillis = MILLIS_IN_DAY * (day - 1);
            millisAfterYear = millisAfterYear + addMillis;
            setTimeInMillis(getTimeInMillis() + addMillis + 1);
         *Returns the day of month.
        public int getDayOfMonth()
            int days = (int)(millisAfterYear / MILLIS_IN_DAY);
            int cntr = 0;
            while (days >= daysInMonth[cntr])
                days = days - daysInMonth[cntr];
                cntr++;
            //Internally this class stores dates starting at zero, but i want it to look like it starts at 1.
            return days + 1;
         *Sets the time to the currently selected day at the passed hour on the hour. uses 24 hour clock.
        public void setHour(int hour)
            if (hour < 0 || hour > 23)
                throw new ArrayIndexOutOfBoundsException(hour);
            setDayOfMonth(getDayOfMonth());
            long addMillis = MILLIS_IN_HOUR * hour;
            millisAfterYear = millisAfterYear + addMillis;
            setTimeInMillis(getTimeInMillis() + addMillis);
         *Returns the hour (but not how many minutes past the hour).
        public int getHour()
            long millisAfterDay = millisAfterYear % MILLIS_IN_DAY;
            return (int)(millisAfterDay / MILLIS_IN_HOUR);
         *Set the minutes past the hour. Works 0-59.
        public void setMinute(int minute)
            if (minute < 0 || minute > 59)
                throw new ArrayIndexOutOfBoundsException(minute);
            setHour(getHour());
            long addMillis = MILLIS_IN_MINUTE * minute;
            millisAfterYear = millisAfterYear + addMillis;
            setTimeInMillis(getTimeInMillis() + addMillis);
         *Returns the minutes past the hour, 0-59.
        public int getMinute()
            long millisAfterHour = millisAfterYear % MILLIS_IN_HOUR;
            return (int)(millisAfterHour / MILLIS_IN_MINUTE);
         *Sets the seconds past the minute, 0-59.
        public void setSecond(int second)
            if (second < 0 || second > 59)
                throw new ArrayIndexOutOfBoundsException(second);
            setMinute(getMinute());
            long addMillis = MILLIS_IN_SECOND * second;
            millisAfterYear = millisAfterYear + addMillis;
            setTimeInMillis(getTimeInMillis() + addMillis);
         *Returns the seconds past the minute, 0-59.
        public int getSecond()
            long millisAfterMinute = millisAfterYear % MILLIS_IN_MINUTE;
            return (int)(millisAfterMinute / MILLIS_IN_SECOND);
         *The more commonly seen set method of other date objects. Sets the date/time to 00:00 of the year/month/day passed. Convenience method
         *for setDate(int year, int month, int day, int hour, int minute, int second).
        public void setDate(int year, int month, int day)
            setDate(year, month, day, 0 , 0 , 0);
         *Sets every date/time field.
        public void setDate(int year, int month, int day, int hour, int minute, int second)
            setYear(year);
            setMonth(month);
            setDayOfMonth(day);
            setHour(hour);
            setMinute(minute);
            setSecond(second);
         *Returns yes if the stored date is a leap year. A leap year is every year that is divisible by four unless it is divisible by 100
         *unless it is also divisible by 400.
        public boolean isLeapYear()
            return isLeapYear(this.year);
         *For internal use. Returns if the passed year meets the criteria for a leap year.
        private boolean isLeapYear(int year)
            boolean leapYear = false;
            if (year % 4 == 0)
                if (year % 100 != 0)
                    leapYear = true;
                else if (year % 400 == 0)
                    leapYear = true;
            return leapYear;
         *Returns the difference in milliseconds between the time stored in this object and the millis passed to this method.
        public long getDifferenceInMillis(long millis)
            return getTimeInMillis() - millis;
         *Returns the difference in milliseconds between this date and the date passed to this method.
        public long getDifferenceInMillis(AwesomeDate otherDate)
            return getDifferenceInMillis(otherDate.getTimeInMillis());
         *Designed to be a wrapper method for the getDifferenceInMillis method. This method changes millis into years/days/whatever. Pass
         *the number of milliseconds you have to convert in the first parameter. The second parameter should be the type of denomination you
         *want (year, day, whatever). Use the MILLIS_IN_* fields associated with this object. Also bear in mind when workin with years that
         *some years are leap years, so in extreme cases of differences of 365+ years you may gain/lose a year.
        public static int toGreaterDenom(long millis, long denom)
            return (int)(millis / denom);
         * The first argument is how many of whatever (days, months, years, etc.) to add (use negative numbers to subtract). For the second
         * argument pass one of the MILLIS_IN_* fields. Thus, to add two hours would be
         * <code>
         *      AwesomeDate.adjustDate(2, AwesomeDate.MILLIS_IN_HOUR);
         * </code>
        public void adjustDate(int amount, long typeMillis)
            setTimeInMillis(this.millis + amount * typeMillis);
         *Returns an object of type java.util.Date set to the date/time stored here.
        public java.util.Date toUtilDate()
            long offset = TimeZone.getDefault().getRawOffset();
            return new java.util.Date(getTimeInMillis() +  -1 * offset);
    //        return new java.util.Date(getTimeInMillis());
         *Returns an object of type GregorianCalendar set to the date/time stored here.
        public GregorianCalendar toGregorianCalendar()
            long offset = TimeZone.getDefault().getRawOffset();
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTimeInMillis(getTimeInMillis() - offset);
            return cal;
         *Returns an object of type java.sql.Date set to the date/time stored here.
        public java.sql.Date toSQLDate()
            long offset = TimeZone.getDefault().getRawOffset();
            return new java.sql.Date(getTimeInMillis() - offset);
        /** Format the date  using the string that you pass. Works just like the SimpleDateFormat object. Infact, it uses one! Heres
         *how it works:
         *Letter  Date or Time Component  Presentation  Examples  <br>
         *G  Era designator  Text  AD  <br>
         *y  Year  Year  1996; 96  <br>
         *M  Month in year  Month  July; Jul; 07<br> 
         *w  Week in year  Number  27  <br>
         *W  Week in month  Number  2  <br>
         *D  Day in year  Number  189  <br>
         *d  Day in month  Number  10  <br>
         *F  Day of week in month  Number  2<br> 
         *E  Day in week  Text  Tuesday; Tue  <br>
         *a  Am/pm marker  Text  PM  <br>
         *H  Hour in day (0-23)  Number  0<br> 
         *k  Hour in day (1-24)  Number  24  <br>
         *K  Hour in am/pm (0-11)  Number  0  <br>
         *h  Hour in am/pm (1-12)  Number  12  <br>
         *m  Minute in hour  Number  30  <br>
         *s  Second in minute  Number  55  <br>
         *S  Millisecond  Number  978  <br>
         *z  Time zone  General time zone  Pacific Standard Time; PST; GMT-08:00<br> 
         *Z  Time zone  RFC 822 time zone  -0800  <br>
        public String toFormattedString(String format)
            SimpleDateFormat formattage = new SimpleDateFormat(format);
            return formattage.format(toUtilDate());
         *I overrode the toString method. Now it tells everyone how awesome my AwesomeDate is.
        public String toString()
            String output = "John's Awesome Date!";
            output = output + " Millis: " + getTimeInMillis();
            output = output + " Year: " + getYear();
            output = output + " Month: " + getMonth();
            output = output + " Date: " + getDayOfMonth();
            output = output + " Time: ";
            if (getHour() < 10)
                output = output + "0" + getHour();
            else
                output = output + getHour();
            if (getMinute() < 10)
                output = output + "0" + getMinute();
            else
                output = output + getMinute();
            output = output + " Seconds: " + getSecond();
            return output;
        public static void main(String[] psvm)
            AwesomeDate blah = new AwesomeDate();
            GregorianCalendar blah1 = new GregorianCalendar();
            GregorianCalendar blah2 = new GregorianCalendar();
    }

    The reason Callendar is so complicated is that it is trying to solve a very complicated problem.
    You don't appear to support leap seconds (of which there can be upto 2 in any time interval)
    http://www.timeanddate.com/time/leapseconds.html
    Some of your code will not work for large dates very well (seems to iterate over the years). Try using your date class for astronomical or geological calculations. them big numbers will make your code slow at the moment.
    You don't seem to support timezones or transitory offsets (BST vs GMT). You most definately don't handle changes to timezone offsets that have occured in the past or historical daylight savings time offsets (they have not always been the same)
    The difference between two calendars is a "duration" a duration means nothing unless it is applied to a caledar/date (although you may be able to get away with it if the duration is always stored in millis)

  • Dynamically inserting data to make a report

    Hi all, I am facing a problem with report generation. Currently I am making reports using excel templates. I am attaching the picture of sample template here. As you can see B22 is the location of item 1 and B23 is the location for Description 1. Space for description is fixed. Now B30 is the location for item name 2 and B31 is the location for item description 2. My problem is, if description of the item 1 is very small, that already allocated space will be waste.Or if Description 1 is very large, I cannot accomodate it in the given space. So I need item name 2 to come exactly under description 1, rather than fixing the space for item name 2 and subsequent rows. In short, the allocation should be dynamic, according to the size of the descriptions. Is it possible through LABView? Any ideas?
    I dont need it to be done with excel only. I need that format of my quotation should be same thats all..Is there any other ways to do this?
    Thanks in advance,
    Suvin.
    Attachments:
    example.JPG ‏175 KB

    Do you need to show the measure calculated for those 18 months as a total on 1 row, or do you need to select a single month and then display on row filters 18 distinct rows?
    The first is trivial as driezl has suggested.
    The second will require a second calendar table.
    I created this example workbook for a coworker who had a similar problem. You will have to use the disconnected table as your filter and pull your related table onto the rows.
    Finally, the easiest way to deal with the sort of date arithmetic you need to do is to restructure your date table to have a series of "Sequential" fields. These fields should be the number of units of time since the beginning of your calendar.
    For example, consider a calendar starting on January 1, 2010. For January - December 2010, [MonthSequential] = 1, 2, ..., 12. For January - December 2011, [MonthSequential] = 13, 14, ..., 24, and so on, incrementing by 1 for each sequential month in time.
    Assuming you have this set up in your date tables (one related to your model - DimDate - and one disconnected - DisconDimDate) your measure would look like this:
    18 Month Measure:=
    CALCULATE( [Measure]
    , FILTER( DimDate
    , DimDate[MonthSequential] >= MAX( DisconDimDate[MonthSequential] )
    && DimDate[MonthSequential] <= MAX( DisconDimDate[MonthSequential] ) + 18
    Please review this example along with the workbook I have linked above.

  • Extracting year and date

    I am working on the following query
    SELECT report_date, EXTRACT (MONTH FROM report_date) FROM program_details;
    SELECT a.customer_id, a.report_date as change_date
    FROM program_details AS a
    LEFT JOIN program_details AS b
    on a. customer_id = b. customer_id
    AND EXTRACT (MONTH FROM a.report_date) = EXTRACT (MONTH FROM b.report_date) - 1
    AND EXTRACT (YEAR FROM a.report_date) = EXTRACT (YEAR FROM b.rpt_date )
    WHERE a.code_status = 'Gold' and b.code_status = 'Plat'
    AND a.report_date >= '2007-12-01 00:00:00.0'
    AND a.report_date < '2009-01-01 00:00:00.0'
    I have a table with customer id, yyyy-mm-dd for many years , and status as gold silver or platinum. and I need to work out the month that the status changed, and return a field as year-month.
    I am trying to extract the year and date that a customer changed from gold to plat but I am not sure how date arithmetic works. I need to have output like : customer_id and year-month but I keep just getting month.
    I know this is vague, but if you could help with the part of the query that delivers year and month back that would be great.
    Thank you very much

    Hi,
      1  SELECT a.customer_id, to_char(a.report_date, 'yyyy-mm') as change_date
      2* FROM program_details a
    SQL> /
    CUSTOMER_ID CHANGE_
              1 2009-06Bartek

Maybe you are looking for

  • Capital goods return

    HI ALL MAINTAINED MATERIAL MASTER - WITH CHAPTER ID AND ASSET SETTING. 1. CRAETED PO 2. DO GR 3. J1IEX FOR PART 1 AND 2 4. DO THE TRANSFER CREDIT J2I8 HOW TO DO THE COMPLETE OR PARTIAL REJECTION FOR CAPITAL CASE??? IS THERE NE HEP LINK??? TELL ME THE

  • Empty document in communication channel

    Hi Expert! I need your help. I have a problem with loading file with an old interface and I need to understand why... No exist messagges about the error in monitor. I only find the follow messagge in channel log: Channel CC_123_ABC_Snd: Empty documen

  • [SOLVED] external hard drive permissions

    I have a seagate external hard drive (/dev/sdb1), formatted as ntfs. Whenever i try to make something in the drive, or copy something, i get a Permission Denied error. How can I give rw permissions? I have tried searching around, but i can't find an

  • G5 going funny

    I have a G5 dual 2.0 and the last 3 weeks it has been crashing and the dancing blue pixels problem. I have reinstalled the operating system and after 2 whole days of no problems, it has all started again. The dancing blue pixel problem is back on ran

  • Creating Report using MS Word

    Hi, have an application and i want to be able to output a report with it. This could be a fairly basic document, just with a few number and name that could be different each time. The user should just be able to click a button and the application sho