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

5

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

I'd like to do something like the snippet below, but it did not work:

if (object.getDate().getSeconds() > System.currentTimeMillis())
  //do something
    
asked by anonymous 29.01.2014 / 19:41

2 answers

4

There are two simple ways:

Comparing the time in milliseconds

The getTime() of java.util.Date method returns the time in milliseconds from this January 1, 1970. The same is true for the currentTimeMillis() method. So, just compare the two numbers:

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

Creating a Date with the system date

When you create a new Date() , the constructor initializes the date with the system date. See the implementation:

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

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

if (object.getDate().after(new Date())) { ... }
    
29.01.2014 / 20:14
1

Do as follows:

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

But the right thing to do even if you're using Java below version 8 is to give up Date and use the library Joda- Time . :)

    
29.01.2014 / 19:43