-2

I work with a RichFaces calendar component. I use Rich Faces 3 und have two calendar components.

How it is possible to compare two Date Values in that way, that one to these two value can be higher than to other one?

The two values will be initialize in that way:

Date startDate = new Date();

Date endDate = new Date();

Now my user can select DateValues in Rich Faces Calendar und the selected values will be saved in the variables.

How can i compare this two values?

Greetz

5 Answers5

4

Have you checked the documentation? There are methods for compareTo(), before(), after() etc lots of options for comparison depending on your needs. You could also use the getTime() method to find the milliseconds since epoch of each time, you could then manipulate these to find the timespan between the times.

http://docs.oracle.com/javase/6/docs/api/java/util/Date.html

Robadob
  • 5,319
  • 2
  • 23
  • 32
3

You can use after and before methods

startDate.before(endDate);
startDate.after(endDate);

As Date implements Comperable<Date>, method compareTo also works fine.

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
2

You can use compareTo method of Date to do comparison

The compareTo(Date anotherDate) method returns

the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

sanbhat
  • 17,522
  • 6
  • 48
  • 64
2

compareTo(Date date) is a method of Date class that compares two dates this method :

  • Return value is 0 if both dates are equal.

  • Return value is greater than 0 , if Date is after the date argument.

  • Return value is less than 0, if Date is before the date argument.

     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date1 = sdf.parse("2012-10-31");
    Date date2 = sdf.parse("2013-01-21");
    
    
    if(date1.compareTo(date2)>0){
                    System.out.println("Date1 is after Date2");
                }else if(date1.compareTo(date2)<0){
                    System.out.println("Date1 is before Date2");
                }else if(date1.compareTo(date2)==0){
                    System.out.println("Date1 is same as Date2");
                }else{
                    System.out.println("never gets executed");
                }
    
Bharat
  • 904
  • 6
  • 19
1

To compare your two dates you should use the compareTo() Method:

if(startDate.compareTo(endDate) > 0)

This method

  1. return 0 if the dates are equal
  2. return a positve value if the date is after the date argument
  3. return a negative value if the date is before the date argument
Gerret
  • 2,948
  • 4
  • 18
  • 28