警告以避免将来在Java中使用时间

时间:2011-01-11 18:10:56

标签: java

  

可能重复:
  warning message/pop out for date/time

我有一个表单,用户需要输入日期和时间(2个不同的字段),时间不能在将来。它可以是过去的当前时间或时间,仅在12小时之前。所以我想在时间超过12小时时添加警告信息。如何在Java中计算这个。请帮帮我!

2 个答案:

答案 0 :(得分:1)

如果你想要Java,这应该可行。 JODA很好,但它是另一个lib依赖。

`import java.util.Calendar;    import junit.framework.TestCase;    import static java.lang.System.out;

public class DateCheck扩展TestCase {     public void testCheckBefore(){         //获取当前时间         日历c = Calendar.getInstance();

    //Let's make it 13:00 just to make the example simple.
    c.set(Calendar.HOUR_OF_DAY, 13);
    out.println(c.getTime());

    Calendar old = Calendar.getInstance();
    old.set(Calendar.HOUR_OF_DAY, 0);
    if(old.after(c)) {
        throw new IllegalArgumentException("You entered a date in the future");
    }

    assertTrue(olderThanTwelveHours(c, old));

    // Let's change to 5 in the morning.
    old.set(Calendar.HOUR_OF_DAY, 5);
    assertFalse(olderThanTwelveHours(c, old));
}

private boolean olderThanTwelveHours(Calendar c, Calendar old) {
    long startTime= c.getTimeInMillis();
    long oldTime = old.getTimeInMillis();

    long timeDiff = startTime - oldTime;
    if(timeDiff > (12 * 60 * 60 * 1000)) {
        out.println("You're too late");
        return true;
    }
    return false;
}

}`

答案 1 :(得分:0)

您基本上想要计算2个日期之间的小时差异。您可以使用JodaTime hoursBetween方法轻松完成此操作。