This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Comparing Dates Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparing Dates" Watch "Comparing Dates" New topic
Author

Comparing Dates

Neha Mohit
Ranch Hand

Joined: Apr 25, 2006
Posts: 87
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

Joined: Nov 24, 2005
Posts: 14688
    
  16

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.


[My Blog]
All roads lead to JavaRanch
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

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

Joined: Jan 30, 2000
Posts: 18671
[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 ]

"I'm not back." - Bill Harding, Twister
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

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

Joined: Apr 25, 2006
Posts: 87
Thanx to all of you
 
GeeCON Prague 2014
 
subject: Comparing Dates