0

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.

4

2 回答 2

0

您应该Calendar使用方便比较日期。

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

而且你可以随时格式化

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss   dd/MM/yyyy");
String currentDate = sdf.format(c1.getTime());
于 2013-08-26T19:19:23.407 回答
0

如果您只有两个String对象是可用的日期。您将需要在您自己的比较器类或另一个对象中处理它们。在这种情况下,由于这些已格式化为日期,您只需创建Date对象并使用之前发布的方法进行比较。像这样的东西:

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
}  
于 2013-08-27T00:10:35.077 回答