Problem comparing dates (times) in Android

2019-04-01 21:09发布

I am having a problem when i am trying to compare two dates in Android. I am not sure if it is a problem with the emulator or if i have a problem in the code itself. The thing is the code works in a normal Java program environment, which confuses me even more.

I have the following code to compare dates in Android 2.1 :

public boolean compareDates(String givenDateString) {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    boolean True;
    try {
        True = false;
        Date givenDate = sdf.parse(givenDateString);
        Date currentDate = new Date();

        if(givenDate.after(currentDate)){
            True = true;
        } if(givenDate.before(currentDate)){
            True = false;
        } if(givenDate.equals(currentDate)){
            True = false;
        }   
    } catch (Exception e) {
        Log.e("ERROR! - comparing DATES", e.toString());
    }
    return True;
}

now the code works well in Java, but in Android it keeps returning me false. The only change happens when i insert the currentDate variable with a string like this:

Date currentDate = sdf.parse("16:50");

With the currentDate variable set in a string it returns true when i compare it with a value that's after the time given. I have also tried setting the currentDate variable with:

  Calendar calendar = Calendar.getInstance();
  Date currentDate = calendar.getTime();

I am completely at a loss here. Hoping someone has any ideas on what might be a problem here.

--- EDIT ---

Found the solution for my problem. I used the calendar and read the hour and minute from there, then i put them in a string to parse and it worked. The code now looks like this:

public boolean compareDates(String givenDateString) {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    boolean True = false;
    try {
        Date givenDate = sdf.parse(givenDateString);
        Calendar now = Calendar.getInstance();
            int hour = now.get(Calendar.HOUR_OF_DAY);
            int minute = now.get(Calendar.MINUTE);
        Date currentDate = sdf.parse(hour + ":" + minute);

        if(givenDate.after(currentDate)){
            True = true;
        } if(givenDate.before(currentDate)){
            True = false;
        } if(givenDate.equals(currentDate)){
            True = false;
        }   
    } catch (Exception e) {
        Log.e("ERROR! - comparing DATES", e.toString());
    }
    return True;
}

1条回答
闹够了就滚
2楼-- · 2019-04-01 22:07

When I'm doing comparisons on dates, I make sure to use Calendar objects. Then I use the compareTo() function:

if ( myCalendar.compareTo(upperLimitCalendar) >= 0 )

See the documentation here:

http://developer.android.com/reference/java/util/Calendar.html

查看更多
登录 后发表回答