How to compare Date class to System.currentTimeMillis() in Java?

Asked

Viewed 2,102 times

5

How to compare if a Date object, for example "2014-01-29 00:00:00" is larger than the date of the current system, for example System.currentTimeMillis() in Java?

I would like to do something like the section below, but it didn’t work:

if (object.getDate().getSeconds() > System.currentTimeMillis())
  //do something
  • 1

    This snippet of code is the answer or an attempt that didn’t work?

  • A failed attempt.

  • 1

    Thank you for clarifying!

2 answers

4


There are two simple ways:

Comparing time in milliseconds

The method getTime() of java.util.Date returns the time in milliseconds since January 1, 1970. The same occurs with the method currentTimeMillis(). So just compare the two numbers:

if (object.getDate().getTime() > System.currentTimeMillis()) { ... }

Creating a Date date of the system

By creating a new Date(), constructor initializes date with system date. See implementation:

public Date() {
    this(System.currentTimeMillis());
}

So just check if your date is higher, like this:

if (object.getDate().after(new Date())) { ... }

1

Do it this way:

if (object.getDate().after(new Date(System.currentTimeMillis()))
    // do something

But even if you are using Java below version 8 is sure to let go of Date and use the library Joda-Time. :)

  • Agreeing with the above answer, Joda is much simpler to manipulate and validate dates. Also, you’ll get used to the logic until the new Java 8 Dates API is officially released.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.