[Java] About date period judgment/past future judgment

1 minute read


Seriously recommended to judge the magnitude in milliseconds *Java is taken as an example, but the same story applies to any language.

  • Good children should use Joda-Timewithoutusingjava.util.Date,orusetheTimeAPIifJava1.8orlater.)

** *This is just a reference code. Don’t use the deprecated constructor of the Date class**

Date nowDate= new Date();
// Outputs "It's during the campaign period" in the case of 2020/4/1 00:00:00 to 2020/4/30 23:59:59
if (nowDate.getTime() >= new Date(2020, 3, 1, 0, 0, 0).getTime()
    && nowDate.getTime() <new Date(2020, 4, 1, 0, 0, 0).getTime()) {
    System.out.println("Campaign is in progress");


What are you guys doing with Java date determination? When using java.util.Date class, do you use after method or before method? There are similar methods in Joda-Time and Time API, right?

However, honestly, I can’t immediately judge by just looking at the method, “Is the argument the future? Is it the past? Is the specified date included or not?” Hmm. (It’s stupid)

If you look at the JavaDoc, they are written as follows. (Quoted from Java Doc for Java 1.8)

  • after

Determines if this date is after the specified date.

  • before

Determines if this date is before the specified date.

In other words, neither includes the “specified day itself”. Those who are good at English may understand that after and before mean “not include”, I didn’t know.

As a good Poka, In the case of “Let’s make the campaign application period from 00:00:00 on April 1, 2020 to 23:59:59 on April 30, 2020!”

Date nowDate = new Date();

if (nowDate.after(new Date(2020, 3, 1, 0, 0, 0))
    && nowDate.before(new Date(2020, 4, 1, 0, 0))) {
    System.out.println("Campaign is in progress");

By doing it like this, I am creating a bug that “I can not apply at the moment when the date changes!” (Well, it depends on the project whether the 1 second is good or not)

That’s why it’s better to make a numerical comparison and compare the sizes. It was a story.