0

我已经尝试了很长时间。
我有今天的日期,我想将它与特定日期进行比较。

但是当我像这样设置特定日期时,它给了我错误的输出:

    Calendar cal;
    SimpleDateFormat dateformatter;
    String currentdate;
    cal = Calendar.getInstance();
    dateformatter = new SimpleDateFormat("yyyy-MM-dd");

    //Getting today's date
    currentdate = dateformatter.format(cal.getTime());
    Log.i(Class_Tag, "current = " + currentdate);

    //Setting specific date
    Date start = cal.getTime();
    cal.set(2012, 06, 20);
    Date end = cal.getTime();
    Log.i(Class_Tag, "end = " + dateformatter.format(end));

    long diff = end.getDate() - start.getDate();
    Log.i(Class_Tag, "diff : " + diff);

    long diff1 = end.getMonth() - start.getMonth();
    Log.i(Class_Tag, "diff mnth : " + diff1);

    long diff2 = end.getYear() - start.getYear();
    Log.i(Class_Tag, "diff yr : " + diff2);

    if (start.compareTo(end) == 0) {
        Log.i(Class_Tag, "EQUAL");
    } else if (start.compareTo(end) < 0) {
        Log.i(Class_Tag, "end b4 start, delete");
    } else {
        Log.i(Class_Tag, "start b4 end, do nothing");

输出:

current = 2012-06-20
end = 2012-07-20 ////WHY it is showing month as '7' when I've set it to '6'?
diff : 0
diff mnth : 1 //Because of the wrong month in end date, this comes 1 instead of 0
diff yr : 0
end b4 start, delete //this also is not correct

我尝试了几种解决方案,但没有任何收获。

我唯一的目标是了解该特定日期是否已超过今天的日期。

任何帮助表示赞赏。


编辑

在下面的代码片段中,

//Setting specific date
    Date start = cal.getTime();
    cal.set(2012, 06, 20);
    Date end = cal.getTime();

如果我设置cal.set(2012, 06, 20);cal.set(2012, 05, 20);,则月份差异。出来为 0。

这意味着month特定日期会增加“1”,但是 为什么

4

3 回答 3

2

试试这个;

Calendar cal = Calendar.getInstance();

long dateNowMillis = cal.getTimeInMillis();

cal.set(2013, 1, 23);

long specDate = cal.getTimeInMillis();

if(dateNowMillis > specDate)
{
    System.out.println("Passed");
}
else if(dateNowMillis == specDate)
{
    System.out.println("Now");
}
else
{
    System.out.println("Not passed");
}
于 2012-06-20T05:59:09.180 回答
1

仅供参考,一个月由 0 到 11 的整数表示;0 是一月,1 是二月,以此类推;因此 11 是 12 月。

您可以在此处查看有关Date的更多信息以及有关SimpleDateFormat的更多信息。

更新:

关于getMonth() => 它已被弃用的另一件事Calendar.get(Calendar.MONTH),请查看此处

于 2012-06-20T05:52:41.173 回答
1

@GAMA 像这样你会得到:

yourDate.setDate(yourDate.getDate() - daysToSubtract);

希望能帮助到你。

于 2012-06-20T06:04:30.053 回答