当前位置: 动力学知识库 > 问答 > 编程问答 >

warning to avoid time in future in Java

问题描述:

Possible Duplicate:

warning message/pop out for date/time

I have a form where a user need to enter date and time (2 different fields) and the time cannot be in future. It can either be current time or time in past only to 12 hours before. So I want to add a warning message when the time is older than 12 hours. How will be the calculation of this in Java. Please help me out!

网友答案:

If you want Java this should work. JODA is good, but it is another lib dependency.

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

public class DateCheck extends TestCase { public void testCheckBefore(){ //Gets the current time Calendar 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;
}

}`

网友答案:

You are basically wanting to calculate the hours difference between 2 dates. You can easily do that using JodaTime hoursBetween method.

分享给朋友:
您可能感兴趣的文章:
随机阅读: