Results 1 to 2 of 2

Thread: Comparing two Dates!

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jun 2005
    Posts
    265

    Comparing two Dates!

    Hello!
    I want to allow the user to enter a date (Year/Month/Day) and then compare it with today's date ... if it before,after, or equal ...
    I wrote one but I don't know what is wrong with!
    Code:
    import java.util.*;  
    public class tt {      
    public static void main(String args[])    {              
    Date t = new Date();
    
    GregorianCalendar today = new GregorianCalendar();
    System.out.println(today.YEAR+" "+(t.getMonth()+1)+" "+today.DAY);
    GregorianCalendar myDate = new GregorianCalendar(2007,12,24);
     
    
    System.out.println(today.compareTo(myDate)+"\n");   
     if(today.compareTo(myDate)<0)         
     System.out.println("Today Date is Lesser than my Date");      
     else if(today.compareTo(myDate)>0)         
     System.out.println("Today Date is Greater than my date");       
     else         
     System.out.println("Both Dates are equal");        
     }
     }
    thanks

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Comparing two Dates!

    This is the same example you posted but better formatted and with no compile errors
    Code:
    import java.util.GregorianCalendar;
    
    public class Test {
    
        public static void main(String args[]) {
            GregorianCalendar today = new GregorianCalendar();
            GregorianCalendar myDate = new GregorianCalendar(2007, 12, 24);
    
            System.out.println(today.compareTo(myDate) + "\n");
            if (today.compareTo(myDate) < 0) {
                System.out.println("Today Date is Lesser than my Date");
            } else if (today.compareTo(myDate) > 0) {
                System.out.println("Today Date is Greater than my date");
            } else {
                System.out.println("Both Dates are equal");
            }
        }
    }
    You might just want to know that the main reason you're getting incorrect result is because what you are calling today is actually "Now" including the time fragment of the date not just the date itself
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width