Comparing Dates


if (date1.equals(date2)) {     System.out.println("dates are the same."); } else {      if (date1.before(date2)) {          System.out.println("date1 before date2");      }      else {          System.out.println("date1 after date2");      } }



In this phrase, we make use of the equals() and before() methods of the Date class. The equals() method will return true if the data values are the same; otherwise it will return false. The dates must be the same down to the millisecond in order for the equals() method to return true. The before() method returns true if the date on which it is called occurs before the date passed as a parameter to this method.

The Date class also has an after() method, which is used similarly to the before() method to determine if the date on which it is called occurs after the date passed in as a parameter.

Another useful method for comparing two dates is the compareTo() method of the Date class. The compareTo() method accepts a date argument and returns an integer value. A value of 0 is returned if the date on which it is called is equal to the date argument. A value less than 0 is returned if the date on which the method is called occurs before the date argument, and a value greater than 0 if the date occurs after the date argument.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net