0

我目前正在做一个项目,其中包括检查项目是否提前或超出了分配的时间。

我从数据库中检索项目的开始日期 (yyyy-MM-dd) 和项目应持续的月数。我还使用检索今天的日期Calendar.getInstance()

我需要的是一种方法来检查今天的日期是否在预计的时间内。

任何帮助将不胜感激!

不要让所有其他不相关的代码让您感到厌烦,这是我正在处理的部分。

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();

String today =  dateFormat.format(cal.getTime());
String startdate = project.getStart();
String duration = project.getDur();
4

1 回答 1

0

So something along the lines of...

Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.add(Calendar.MONTH, duration);

Date endDate = cal.getTime();
Date today = new Date();

// You also want to check for today.equals(endDate)
if (today.before(endDate)) {
    // All is good...
} else {
    // PANIC NOW!!
}

Note. This takes into account the time as well...

If the time is not a factor in your calculations, I tend to move it to either the start of the day or end of the day, depending on what your requirements would be...

public static Date toEndOfDay(Date date) {

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    // Move the time to end of the day...
    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.MILLISECOND, 999);

    return cal.getTime();

}

public static void main(String[] args) {

    Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);
    cal.add(Calendar.MONTH, duration);

    Date endDate = toEndOfDay(cal.getTime());
    Date today = toEndOfDay(new Date());

    // You also want to check for today.equals(endDate)
    if (today.before(endDate)) {
        // All is good...
    } else {
        // PANIC NOW!!
    }

}
于 2013-02-11T04:09:23.990 回答