Narendra
Narendra

Reputation: 5773

Comparing 2 dates using following format yyyy:MM:dd hh:mm:ss

I need to compare two dates along with time portion.

I need to check it upto hh:mm:ss only.

Can any one suggest any util i can use for it or any suggestion for doing programatically.

Thanks,

Narendra

Upvotes: 1

Views: 2719

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533620

To compare just the date portion, the simplest thing to do is

 int cmp = date1.substring(0, 10).compareTo(date2.substring(0,10));

You don't need to convert them into a true date object as the strings will be in the same order. This is like @rodion's answer except his will compare the time as well.

If performance IS important to you I suggest you leave the strings as strings, converting them to a date object is relatively expensive.

Upvotes: 1

rodion
rodion

Reputation: 15029

You can use string comparison like: "2010:01:01 00:00:01".compareTo("2010:01:01 00:00:02"). This will return -1, 0 or 1 for when the first date is before, same or after the second date respectively

If you have the Date or Calendar object available you can compare dates using Calendar.before(date) and Calendar.after(date) methods, but this will take into account milliseconds so you have to be careful to reset milliseconds to 0 before comparing.

If performance is not so important to you I would suggest string comparison above.

Upvotes: 0

Cameron Skinner
Cameron Skinner

Reputation: 54356

You could use a java.text.SimpleDateFormat to parse your dates into Date objects, then use getTime to do the comparison. Date also implements Comparable so you can use that directly if you prefer.

Upvotes: 0

Related Questions