-4

I have a date [format - dd/mm/yyyy]. I need to compare it with the current date so that I can execute this logic

if(end date is in the future) {
//logic
} else {
//logic
} 

Can we do this in JAVA ?

4 Answers4

1

It looks like you are starting with a string so you can use SimpleDateFormat.parse to convert the String to a Date.

Then you can use the compareTo function on the Date class to see if it is in the past or not.

Something like the below (I havent compiled this...)

if (new SimpleDateFormat("dd/MM/yyy").parse(yourSring).compareTo(new Date()) > 0) {
   ...
}

If possible I would always use JodaTime thought instead of the Java Date and Calendar classes. It is much easier to use.

RNJ
  • 15,272
  • 18
  • 86
  • 131
  • You can use Date#after(Date) instead of compareTo to shorten the code somewhat. And why is "DateTime.parse(s, DateTimeFormat.forPattern("dd/MM/yyyy")).isAfterNow()" with Joda (or is it possible to do the same with shorter code?) much easier than "new SimpleDateFormat("dd/MM/yyyy").parse(s).after(new Date())" with the builtin API? – jarnbjo Oct 02 '12 at 13:11
0

In general, use Joda Time:

DateTime.parse("...").isAfterNow();

You will probably want to pass an appropriate DateTimeFormatter, such as DateTimeFormat.forPattern("d/M/y"), as the second parameter.

Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
0

use compareto method to compare two dates. check here in Date API

if(curreDate.compareTo(thisdate)>0) {
// do your logic
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106
-1
if(endDate.after(new Date())){}

just compare to a new Date it will be created a date time of now.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311