Comparing two Calendar dates

No question. Just a comment with code example.
Yesterday I was having issues comparing two Calendar dates. They looked equal in my println statement, but they failed the test. The solution evaded my cafeine intensified brain for hours. Then it hit me. Print out the time in milliseconds and see if the numbers were the same. Nope. Why?
The problem was that in the real world, you get dates from all over the place, not just cooked up for a text book example. (Don't you just hate those text book examples in their unrealistic world?) Anyway, I was getting a date from an HTML form and a data from a database and comparing the two once I had converted them both to a Calendar object. This seemed a reasonable choice.
Well, the java.sql.Date that the Oracle driver returned which was converted to a java.util.Date was fine. I ran this into a Calendar with the call calS.setTime(dbDate). The form date was split into fields and put into a difference Calendar obj with the call calF.set(fYear, fMonth, fDay, 0, 0, 0). This too seemed reasonable. Then a call to calS.equls(calF) resulted in a false even though the actual dates were in fact the same.
The problem was with the time. The java.sql.Date (calS) had a time of 00:00:00 which was fine. The calendar from the form also had 00:00:00 for a time since I initialized it with zeros. Hummmmm. Now what? As mentioned before, I decided to print out the actuall time in milliseconds and that gave me my answer. The two calendars were off by only milliseconds, but that's why. You see, the equals method of Calendar compares two dates/time in milliseconds. You can see this in the source for yourself. It's not difficult to read at all. Download and open the api source file, src.zip, and locate Calendar.java in the java.util directory.
The fix was to add calF.set(Calendar.MILLISECOND, 0) and calS.set(Calendar.MILLISECOND, 0) to zero out the milliseconds in each Calendar object. That did the trick. Here's example code of the problem (test1) and the solution (test2). I tried to simulate as close to real world as possible. If you have a better solution or I've made some error, please let me know. I'm always looking for better ways.
Main.java
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
    private int fYear = 2003;
    private int fMonth = 3;  // march
    private int fDay = 14;
    public static void main(String[] args) {
        Main main = new Main();
        main.test1();
        main.test2();
    public void test1() {
        SimpleDateFormat df = new SimpleDateFormat();
        // get the date from the form
        Calendar calF = Calendar.getInstance();
        calF.set(fYear, fMonth-1, fDay, 0, 0, 0);  // month starts at 0 - so march would be 2
        System.out.println("From form date:     [" + df.format(calF.getTime()) + "] [" + calF.getTimeInMillis() + "]");
        // simulate other activity in the app
        try {
            Thread.sleep(5000);
        catch (Exception ex) {
            ex.printStackTrace();
        // get the Date from the shared object which comes from a database (java.sql.Date)
        // the return is java.util.Date
        // convert to a Calendar
        SharedObject so = new SharedObject();
        Date myDate = so.getTheDate();
        Calendar calS = Calendar.getInstance();
        calS.setTime(myDate);
        System.out.println("Shared Object date: [" + df.format(calS.getTime()) + "] [" + calS.getTimeInMillis() + "]");
        // compare the two calendars for equality
        if (calS.equals(calF)) {
            System.out.println("The same");
        else {
            System.out.println("NOT the same");
    public void test2() {
        SimpleDateFormat df = new SimpleDateFormat();
        // get the date from the form
        Calendar calF = Calendar.getInstance();
        calF.set(fYear, fMonth-1, fDay, 0, 0, 0);
        calF.set(Calendar.MILLISECOND, 0);  // the magic bean
        System.out.println("From form date:     [" + df.format(calF.getTime()) + "] [" + calF.getTimeInMillis() + "]");
        // simulate other activity in the app
        try {
            Thread.sleep(5000);
        catch (Exception ex) {
            ex.printStackTrace();
        // get the Date from the shared object which comes from a database (java.sql.Date)
        // the return is java.util.Date
        // convert to a Calendar
        SharedObject so = new SharedObject();
        Date myDate = so.getTheDate();
        Calendar calS = Calendar.getInstance();
        calS.setTime(myDate);  // just to be safe
        calF.set(Calendar.MILLISECOND, 0);
        System.out.println("Shared Object date: [" + df.format(calS.getTime()) + "] [" + calS.getTimeInMillis() + "]");
        // compare the two calendars for equality
        if (calS.equals(calF)) {
            System.out.println("The same");
        else {
            System.out.println("NOT the same");
SharedObject.java
public class SharedObject {
    public java.util.Date getTheDate() {
        java.util.Date d = null;
        try {
            java.sql.Date s = java.sql.Date.valueOf("2003-3-14");  // this march is converted internally
            d = (java.util.Date)s;
        catch (Exception ex) {
            ex.printStackTrace();
        return d;
} The output
From form date:     [3/14/03 12:00 AM] [1047621600296]
Shared Object date: [3/14/03 12:00 AM] [1047621600000]
NOT the same
From form date:     [3/14/03 12:00 AM] [1047621600000]
Shared Object date: [3/14/03 12:00 AM] [1047621600000]
The same

So your post boils down to the fact that Calendar's set(year, month, day, hour, minute, second) method doesn't change the milliseconds fraction?
Given that there is this method, I guess it would be nice if there was a method that simultaneously set all fields, but the API does state:
Previous values of other fields are retained. If this is not desired, call clear() first.

Similar Messages

  • Stored Procedure to compare two tables data

    Hello,
    I want to have a Stored Procedure which will compare data (only a single column) of two tables and delete the row which is not present in the second table.
    For eg.,
    I have got 2 tables called Table1 and Table2, which have the same column called ID(PK).
    The data in Table1 is 1,2,3 and data in Table2 is 1,3. When the stored procedure runs, it has to compare the ID column in Table1 to ID column in Table2 and since '2' is not there in Table2, I want to delete this row from Table1.
    Thanks in advance.

    user11281601 wrote:
    Hello,
    I want to have a Stored Procedure which will compare data (only a single column) of two tables and delete the row which is not present in the second table.
    For eg.,
    I have got 2 tables called Table1 and Table2, which have the same column called ID(PK).
    The data in Table1 is 1,2,3 and data in Table2 is 1,3. When the stored procedure runs, it has to compare the ID column in Table1 to ID column in Table2 and since '2' is not there in Table2, I want to delete this row from Table1.
    Thanks in advance.
    delete from table1 where id_column in
    (select id_column from table1
    minus
    select id_column from table2);

  • How to compare two tables data...need sql report or utility to find differe

    Hi,
    We have a requirement where we are asked to find data differences between two tables and one of the tables reside on remote database. The database version is same ( 10g ) and datatypes for the tables are similar.
    The client is looking for a sql report or kind of utility to display the data differences for each column ( if possible count differences ) with some meaningful error messages.
    Could anyone let me know the best possible way of doing it..?
    Thanks
    Hitarth

    Hi,
    I found something for tables comparison but getting one error...can you check this please and let me know what is wrong
    Here is the function:
    CREATE OR REPLACE FUNCTION compare_query_results (
    p_query1 IN VARCHAR2
    , p_query2 IN VARCHAR2
    , p_raise_error_if_not_equal IN BOOLEAN DEFAULT FALSE
    , p_raise_error_if_no_rows IN BOOLEAN DEFAULT FALSE
    RETURN NUMBER
    IS
    -- Constants
    c_query_results_equal CONSTANT PLS_INTEGER := 0;
    c_query_results_not_equal CONSTANT PLS_INTEGER := 1;
    oracr CONSTANT VARCHAR2 (1) := CHR (10);
    -- Variable Declaration
    v_sql_stmt VARCHAR2 (32767);
    v_record_count PLS_INTEGER;
    v_return_code PLS_INTEGER;
    v_record DUAL.dummy%TYPE;
    v_result_set_has_rows BOOLEAN;
    -- Ref Cursors
    v_cursor sys_refcursor;
    -- Custom Defined-Exceptions
    result_sets_do_not_match EXCEPTION;
    query_returns_no_rows EXCEPTION;
    BEGIN
    -- Get the count of differing records between p_query1 and p_query2
    dbms_output.put_line('Start-1');
    v_sql_stmt :=
    ' (SELECT /*+ materialize */'
    || SUBSTR (p_query1, INSTR (UPPER (p_query1)
    , 'SELECT'
    , 1
    , 1
    ) + 6)
    || ')
    , (SELECT /*+ materialize */'
    || SUBSTR (p_query2, INSTR (UPPER (p_query2)
    , 'SELECT'
    , 1
    , 1
    ) + 6)
    || ')
    SELECT ''X''
    FROM (
    (SELECT * FROM test1 MINUS SELECT * FROM test2)
    UNION ALL
    (SELECT * FROM test2 MINUS SELECT * FROM test1)
    dbms_output.put_line('Start-2');
    OPEN v_cursor
    FOR v_sql_stmt;
    dbms_output.put_line('Start-3');
    FETCH v_cursor
    INTO v_record;
    dbms_output.put_line('Start-4');
    v_result_set_has_rows := v_cursor%FOUND;
    dbms_output.put_line('Start-5');
    CLOSE v_cursor;
    dbms_output.put_line('Start-6');
    -- If there are rows - the result sets do NOT match...
    IF v_result_set_has_rows
    THEN
    v_return_code := c_query_results_not_equal;
    IF p_raise_error_if_not_equal
    THEN
    RAISE result_sets_do_not_match;
    END IF;
    -- If there are no rows - the result sets do match...
    ELSIF NOT v_result_set_has_rows
    THEN
    IF p_raise_error_if_no_rows
    THEN
    -- Check to make sure that the queries contain rows if desired...
    v_sql_stmt := 'SELECT ''X''
    FROM (' || oracr || p_query1 || oracr || ')';
    OPEN v_cursor
    FOR v_sql_stmt;
    FETCH v_cursor
    INTO v_record;
    IF v_cursor%NOTFOUND
    THEN
    CLOSE v_cursor;
    RAISE query_returns_no_rows;
    END IF;
    CLOSE v_cursor;
    END IF;
    v_return_code := c_query_results_equal;
    END IF;
    RETURN v_return_code;
    EXCEPTION
    WHEN result_sets_do_not_match
    THEN
    raise_application_error (-20101, 'The Queries'' result sets do NOT match. Error returned
    as requested.');
    WHEN query_returns_no_rows
    THEN
    raise_application_error (-20102, 'The Queries'' result sets match, however they contain no
    rows. Error returned as requested.');
    WHEN OTHERS
    THEN
    -- Raise the error
    raise_application_error (-20103
    , 'There is a syntax or semantical error in one or both queries
    preventing comparison.'
    || oracr
    || 'Error Stack :'
    || oracr
    || DBMS_UTILITY.format_error_stack ()
    || oracr
    || 'Error_Backtrace:'
    || oracr
    || DBMS_UTILITY.format_error_backtrace ());
    END compare_query_results;
    I have created two tables ( test1 and test2 ) with few columns and with the same datatypes and executed the above function...I am getting error as folliowing:
    DECLARE
    ERROR at line 1:
    ORA-20103: There is a syntax or semantical error in one or both queries
    preventing comparison.
    Error Stack :
    ORA-00900: invalid SQL statement
    Error_Backtrace:
    ORA-06512: at "ORAOWNER.COMPARE_QUERY_RESULTS", line 53
    ORA-06512: at "ORAOWNER.COMPARE_QUERY_RESULTS", line 121
    ORA-06512: at line 12
    Could someone please help me fixing this error..It would be really appreciated
    Thanks
    Hitarth

  • Any calendar app that can display two calendars per day side by side?

    Is there any app that can display two calendars (data sync with iCloud Calendars) side by side?  e.g. one calendar for planning and the other for actual / diary.

    Calendar can have two or more calendars calendars listed at the same time.
    Each can be a different color for identifidation.
    The first screenshot shows that the Medical and Joint calendars are shared calendars.
    Will that work for you?

  • How to get the Maximum of two calender dates in OBIEE 11g Analytics

    Hi,
    I have requirement like getting the  maximum calendar date from two calendar dates in obiee 11g reports and  the requirement is like the following
    max(Reported.Calendar date, Returned.Calendar Date)
    can anyone help me to solve this issue.
    Thanks,

    Something like this...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select to_date('17-nov-2006','dd-mon-yyyy') as c_start_date, to_date('21-jan-2008','dd-mon-yyyy') as c_end_date from dual union all
      2             select to_date('21-nov-2006','dd-mon-yyyy'), to_date('17-feb-2008','dd-mon-yyyy') from dual union all
      3             select to_date('21-jun-2006','dd-mon-yyyy'), to_date('17-jul-2008','dd-mon-yyyy') from dual
      4             )
      5  -- end of test data
      6  select c_start_date, c_end_date
      7        ,trunc(months_between(c_end_date, c_start_date) / 12) as yrs
      8        ,trunc(mod(months_between(c_end_date, c_start_date), 12)) as mnths
      9        ,trunc(c_end_date - add_months(c_start_date, trunc(months_between(c_end_date, c_start_date)))) as dys
    10* from t
    SQL> /
    C_START_D C_END_DAT        YRS      MNTHS        DYS
    17-NOV-06 21-JAN-08          1          2          4
    21-NOV-06 17-FEB-08          1          2         27
    21-JUN-06 17-JUL-08          2          0         26
    SQL>But, don't forget that different months have different numbers of days, and leap years can effect it too.

  • Calendar date prompts

    I am on 11.1.1.5. I am creating two calendar date prompts begin date and end date for an analysis. I want to be able to generate some kind error message or warning if the user tries to enter a date smaller than begin date in end date prompt. How can I do this?

    @Amith, no the link would not accurately satisfy the OP's need. What if the user chooses a valid date (i.e., in the allowable date range), but the report produces no records? The customized "No Results" message, would say, "Please choose a valid date value" and would be incorrect.
    user12301184 wrote:
    I am on 11.1.1.5. I am creating two calendar date prompts begin date and end date for an analysis. I want to be able to generate some kind error message or warning if the user tries to enter a date smaller than begin date in end date prompt. How can I do this?@user12301184, what you need to do is this:
    1) Create a small report that returns rows if the dates selected in the dashboard prompts are in the valid range, and does not return rows if the dates chosen are outside the range.
    2) In the dashboard, move a Section to the workspace and put your main report there. Click on Section>Properties>Guided Navigation and have OBIEE point to the small report created in step 1 with the radio button "Display when report returns rows" checked off.
    3) Move another Section to the workspace and put a Text object in the Section. Click Section>Properties>Guided Navigation and point to the same report, but this time choose "Dispay if the report returns no rows."
    4) Now in the Text object, put your customized message, "Please choose a valid date range."
    5) Finally, in the report itself, you can customize your "No Results" view to say, "There are no records to display for the date range selected."
    To summarize, according to the OP's criteria, there are two reasons why the report wouldn't show rows: one, specifically because of the invalid date range; and two -- not explicitly stated, but true nonetheless -- when the report itself produces no rows even though the date range is valid.
    My solution takes into account both scenarios. It doesn't give a potential wrong error message like so many applications do when the scenarios are not thought out completely.

  • How to comapare two tables data difference

    Hi all,
    Can any one tell me how to compare two tables data of two different data bases .
    Table names are same in both databases.
    Thanks You
    Regards,
    P Prakash

    833560 wrote:
    I don't have privilege to create data base link ,If the database has no link so that you can query the the data, you have two options.
    Find someone with the privilege to create the link and write a query like this
    Re: Efficient way to comapre two tables.
    Which as I mention may not be quick,
    Kindly tell me some other way .But will be quicker than your other option which is to dump the data into two spreadsheets and start reading.

  • Java 1.3 comparing two dates using Calendar.before(Calendar)

    Has anyone used the Calendar.before() method for comparing two dates, how accurate is this?
    Some users have found problem with this method, is this true?

    manjit84 wrote:
    Has anyone used the Calendar.before() method for comparing two dates, Yes.
    how accurate is this?I've never noticed a problem.
    Some users have found problem with this method, is this true?Check the bug database^1^?
    ^1^ http://bugs.sun.com/

  • Compare Two Date - Very Urgent

    hi to all,
    i want to compare two date..
    i m getting one date from database and having current date..
    what my issue is i want to dispaly error message when database date greater
    than current date value..
    pls help to my problem...

    import java.util.*;
    public class DateVlid {
         public static void main(String[] args)throws ParseException {
              Calendar currentDate=Calendar.getInstance();
              Calendar dbDate=Calendar.getInstance();
              dbDate.set(2007,12,10);
              boolean b=currentDate.before(dbDate);
              if(b){
                   System.out.println("it is before date");
    }Try it once for a while.
    If it has any problems let me know.

  • Is it possible to view/compare two Time Machine desktop dates at the same time?

    I accidentally lost a file on my desktop, inadvertently dragging it onto my browser. I don't know what file I lost, and would like to retrieve it through my Time Machine.  I don't want to replace all of the files on my desktop, but I would like to compare the files from two different dates (current date and last time saved) to discover the file I lost. If there's an easier way to make this discovery, I'm open for suggestions. Otherwise, I wonder if there's a way to see or compare my current   files on desktop vs. my last save to Time Machine (without printing out a list).
    Thanks in advance for your help!

    Hey apple_peeler,
    Thanks for using Apple Support Communities.
    It sounds like you want to find out what is now missing by comparing it with other backups. The Restoring data from Time Machine backups section explains how you can do that.
    Mac Basics: Time Machine backs up your Mac
    http://support.apple.com/kb/HT1427
    You can use the timeline on the right side of the window to reach a certain point back in time. The timeline shows the times of all backups on your backup drive. If you don’t know exactly when you deleted or changed a file, you can use the back arrow to let Time Machine automatically travel through time to show you when that folder last changed.
    Have a nice day,
    Mario

  • Compare two dates in a report

    Hi,
    I would like to compare two dates on a report.
    I would like to compare the opportunity created date and the opportunity modified date. I can't use this formula CASE WHEN Opportunity."Last Modified" = Opportunity."Created Date" then 1 else 0
    I think I have to use TIMESTAMPDIFF but I don't know which interval I have to put to analyze the entire date in this format 31/12/1999 16:49:08
    Thanks a lot for your help
    Regards,

    Hi !
    It depends on the interval you need to compare these dates. If you want to know the number of days between these dates, you'll have to use SQL_TSI_DAY as interval. If it's minutes, you'll need SQL_TSI_MINUTE...
    Here are the possible intervals :
    *SQL_TSI_SECOND, SQL_TSI_MINUTE, SQL_TSI_HOUR, SQL_TSI_DAY, SQL_TSI_WEEK, SQL_TSI_MONTH, SQL_TSI_QUARTER, or
    SQL_TSI_YEAR*
    Hope this will help, feel free to ask more !
    Max

  • Compare two dates in different format.

    Hi
    I want to compare two dates....one of which is in the timeStamp format ("yyyy-MM-dd HH:mm:ss")
    and the other is in java.util.Date i.e Tue Oct 11 10:22:47 GMT+05:30 2005
    Do I have to tokenise and then compare them.Is there any better approach?
    I want to find out which is greater/smaller one.
    Pls help.
    Regards,
    Sandip.

    I would convert both to Date and compare them. To convert String to Date check java.text.SimpleDateFormat and its parse(...) method.
    HTH
    Mike

  • Putting a date in two calendars?

    here's one more question
    i have about 8 different calendars set up in ical. one for business appointments that apply to both myself and my associate, one for family appointments etc.
    I have it set up so that they sync via my .mac account.
    what i often miss is the ability to be able to set one date to two calendars -
    say if i'm out of town on business, that it can appear on my work calendar and my family calendar, without me having to have two entries.
    any ideas?
    cheers, warner

    Select "Provide iCal feedback" from the iCal menu and send Apple a message, is about the best advice I can give you.
    Cheers,
    Nicolas

  • How to Compare two Dates in java

    How to Compare two Date Field after getting the values from jTextField1.getText() and jTextField2.getText().

    Date d1=DateFormat.getDateInstance().parse(yourstring1);
    same for d2
    d1.compareTo(d2);
    could be that i misrememberd the exact naems of some functions or mixed up something in the equence of d1=

  • How to compare two date Objects

    Hi,
    I have two Calendar Objects, one is coming from client and one is my server time, I need to evaluate that incoming time with server time so that if it is sent before an hour back then i should not do anything on that request Object. I have converted the incoming String into Calendar Object and how can i evaluate these two Calendar Objects including their hours and minutes.
    Thanks in advance
    bajju

    bajjurireddy, ignore Mobiquity's post. It contains no useful information and will only serve to confuse and frustrate you.
    Mobiquity wrote:
    Also make sure that the two date objects are in the same date format..
    public static String DateToDateString(java.util.Date d, String dateFormat)
         throws ParseException {
              SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
              sdf.setLenient(false); // this is required else it will convert
              String dateString = sdf.format(d);
              return dateString;

Maybe you are looking for

  • Backup will not restore with migration assistant.

    This is long and complicated but here goes. Had a 10.5 machine PPC that was backing up to a time capsule. IMac blew out PS so was toast. Took it home and took another iMac 10.5 machine that had a bad HD. Put new HD into that machine and installed 10.

  • ITunes shuffling my songs on my computer every 5 seconds. Need help.

    I am having a major problem with My iTunes music shuffling my songs every 5 seconds when I'm not doing anything. Any help would be great. Thank you.

  • UIloader can't find images

    Ok this is my first time useing a forum but I have run into a problem and really need some help dont know if this is where I'm suppose to post it.Here it is building a web site with Flash cs4 and useing a UIloader to bring in my photos and it keeps g

  • Can I buy hp touch smart note book 15-r136 windows 8

    I refreshed my computer not knowing It would erase my power on pass word . 24/7 techies have been been trying online .They got to (enter administrator pass word or power on pass word ). He could not get past this . It's a H P - Touch Smart Laptop 15-

  • CVCcreation longer processingtime with report CL_SQL_RESULT_SET==CP in SM51

    Hi All, We are facing iisue in production while generating CVC's.In the past it ran sucessful and now the job is processing for longer duration say 20 Hrs without any runtime error and failure.When we look in SM51 the status is under the report it's