Comparing formatted dates

709 views Asked by At

I create a date and then format is like this:

Example 1:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss   dd/MM/yyyy");
                    String currentDate = sdf.format(new Date());

What I would like to do is check if this date is before another date (also formatted the same way). How would I go about doing this?

Example 2:

Also, how would I check whether one of these is before another:

long setForLong = System.currentTimeMillis() + (totalTime*1000);
String display = (String) DateFormat.format("HH:mm:ss   dd/MM/yyyy", setForLong);

EDIT:

I think more detail is needed. I create a date in two different ways for two different uses. The first use just formats the current date into a string so it is readable for the user. In the second case, I am using a date in the future with System.currentTimeMillis and adding on a long. Both result in a string.

Both methods format the date in exactly the same way, and I set the strings into a TextView. Later, I need to compare these dates. I do not have the original data/date/etc, only these strings. Becasue they are formatted in the same way, I though it would be easy to compare them.

I have tried the if(String1.compareTo(String2) >0 ) method, but that does not work if the day is changed.

2

There are 2 answers

9
Nick On BEST ANSWER

If you only have two String objects that are dates available to you. You will need to process them in something, either in your own comparator class or in another object. In this case, since these are already formatted into dates, you can just create Date objects and compare using the methods previously posted. Something like this:

String string = "05:30:33   15/02/1985";
Date date1 = new SimpleDateFormat("HH:mm:ss   dd/MM/yyyy", Locale.ENGLISH).parse(string);

String string2 = "15:30:33   01/02/1985";
Date date2 = new SimpleDateFormat("HH:mm:ss   dd/MM/yyyy", Locale.ENGLISH).parse(string2);

if(date1.getTime()>date2.getTime()) {
    //date1 greater than date2
}
else if(date1.getTime()<date2.getTime()) {
    //date1 less than date2
}
else {
    //date1 equal to date2
}  
5
Viacheslav On

You should use Calendar for convenient comparing dates.

Calendar c1 = Calendar.getInstance();
c1.setTime(Date someDate);
Calendar c2 = Calendar.getInstance();
c2.setTime(Date anotherDate);
if(c1.before(c2)){
    // do something
}

And you can format it at any time

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss   dd/MM/yyyy");
String currentDate = sdf.format(c1.getTime());