• Post Reply Bookmark Topic Watch Topic
  • New Topic

compareTo for comparing Dates  RSS feed

 
Gajendra Kangokar
Ranch Hand
Posts: 94
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how does compareTo() work when we are comparing two dates?
I mean what all values in Date is comapred?
suppose I have two dates with same dd/MM/yyyy value but different time.

Thank You


 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First there is a compareTo() method in the java.util.Date class because it implements the Comparable interface. The code (from grepcode):



Using compareTo() and the before()/after()/equals() methods in the Date class work the same way.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java's class java.util.Date is actually a timestamp, not just a year / month / day date.

If you compare two dates with compareTo(), it will compare the full timestamp, down to the millisecond.

If you are using Java 8, then please use the new date and time API, instead of the crappy old java.util.Date and java.util.Calendar. For example, if you need to work with year / month / day dates, use class java.time.LocalDate.
 
Gajendra Kangokar
Ranch Hand
Posts: 94
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes this is what i dint know
Thank you Jesper.
 
Dieter Quickfend
Bartender
Posts: 543
4
Java Netbeans IDE Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're not using Java SE 8, JodaTime is the library used most often for advanced date processing.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!