【问题标题】:Problem comparing dates (times) in Android在 Android 中比较日期(时间)时出现问题
【发布时间】:2011-09-30 11:16:35
【问题描述】:

我在尝试比较 Android 中的两个日期时遇到问题。我不确定这是模拟器的问题还是我的代码本身有问题。 问题是代码在普通的 Java 程序环境中工作,这让我更加困惑。

我有以下代码来比较 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;
}

现在代码在 Java 中运行良好,但在 Android 中它一直返回错误。 当我用这样的字符串插入 currentDate 变量时,唯一的变化发生了:

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

在字符串中设置 currentDate 变量时,当我将它与给定时间之后的值进行比较时,它会返回 true。我也尝试过设置 currentDate 变量:

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

我在这里完全不知所措。希望有人对这里可能存在的问题有任何想法。

--- 编辑---

找到了我的问题的解决方案。我使用日历并从那里读取小时和分钟,然后我将它们放在一个字符串中进行解析并且它起作用了。代码现在看起来像这样:

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;
}

【问题讨论】:

    标签: android date time calendar compare


    【解决方案1】:

    当我对日期进行比较时,我确保使用日历对象。然后我使用 compareTo() 函数:

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

    在此处查看文档:

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

    【讨论】:

    • 感谢您的回答。非常感激。我又查了一些日历,找到了解决问题的方法。再次感谢。
    • 没问题。很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    相关资源
    最近更新 更多