About date period judgment / past / future judgment


Seriously recommended to judge the size in milliseconds

** * This is just a reference code. Let's stop using the deprecated constructor of the Date class **

Date nowDate= new Date();
// 2020/4/1 00:00:00 ~2020/4/30 23:59:In the case of 59, output "It's during the campaign period"
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("During the campaign period");


How are you guys doing 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?

But honestly, I can't immediately judge "Is the argument the future? Is it the past? Does it include the specified date? Does it not?" Just by looking at the method. Hmm. (It's stupid)

If you look at the JavaDoc, it says: (Quoted from JavaDoc for Java 1.8)

Determines if this date is later than the specified date.

Determines if this date is before the specified date.

In other words, neither of them includes the "specified date itself". Those who are good at English may understand that after and before mean "not included", I didn't know.

As a well-done poca When "Let's apply for the campaign 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("During the campaign period");

By doing this, I am creating a bug that says "I can't apply at the moment when the date changes !!!!". (Well, it depends on the project whether or not that one second is good)

Therefore, there is no mistake in making a numerical type and comparing the size. It was a story.

Recommended Posts

About date period judgment / past / future judgment