This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing Dates

 
Neha Mohit
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ranchers,

I was just wondering is there any way to compare to dates in Java, here is the situation i have two dates 26-11-1953 and 26-04-1981 both are in String format . Is there any way to compare them in java .



regards
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to know which one is before/after, you can still use String.compareTo.
If you want to do some more comparison, you can try to use java.util.Calendar.
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Change this string format into java.util.Date Object and then try the method compareTo

public int compareTo(Date anotherDate)Compares two Dates for ordering.

Parameters:
anotherDate - the Date to be compared.
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.


for an Example:


 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Satou]: If you want to know which one is before/after, you can still use String.compareTo.

If you do that, then "26-11-1953" is after "26-04-1981". Because "11" is after "04". The String class doesn't know anything about dates, and so alphabetic comparison is useless here. (Unless the dates had appeared in a sensible format like 1953-11-26 or 1951126, which are easily sortable as strings. But in general normal humans don't do that sort of thing, unfortunately.) To compare these strings correctly, you want to convert them to java.util.Date instances. There are several ways to do this - java.util.Calendar offers some particularly painful ways - but the easiest way is to use java.text.SimpleDateFormat:

[ July 10, 2006: Message edited by: Jim Yingst ]
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim,
you're right, sorry. I lamely assumed that the format was YYYYMMDD...
It doesn't work with DD-MM-YYYY
 
Neha Mohit
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx to all of you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic