简体   繁体   中英

Comparing two Dates in Java

I have an Identity class with necessary accessors and mutators.

In a seperate program I am comparing the Identity's Date to todays date which always returns <= 10 . However when I go to print it I get the same result no matter what the date is. Is there a different way to access the correct date?

I need to get the number of days between two dates and I'm having trouble on the formating:

Date today = new Date();
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

        Date a = df.parse("06/18/2015");
        Date b = df.parse("01/04/2015");
        Date c = df.parse("02/04/2015"); 
        Date d = df.parse("03/04/2015"); 
        Date e = df.parse("07/04/2015"); 
if(a.compareTo(today) == 30{
//do stuff
}

I've tried multiple methods to no avail.

You have two mistakes in your code :

  1. compareTo() will only return 0 if dates are identical, a positive value if the date is after the argument, or a negative value if it is before. It does not return the difference between the two dates. To get the difference you can write :

    today.getTime() - expiration.getTime()

    to get the number of milliseconds between the two dates, and then compare it to 10 days converted in milliseconds.

  2. You don't initialize your date correctly : Date a = new Date(06/18/2015); won't work. It is supposed to create a new Date with a number of milliseconds as a parameter. So your code will divide 6 by 18 and by 2015 to obtain a number of milliseconds... You can use :

    Date a = new GregorianCalendar(2015, 06, 18).getTime();

  3. You have a simpler way to get today : Date today = new Date();

You're performing integer division, not calling the Date constructor you think.

Date a = new Date(06/18/2015);

Use a DateFormat like

public static void main(String[] args) {
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    try {
        Date a = df.parse("06/18/2015");
        System.out.println("1. " + a);
        System.out.println("2. " + df.format(a));
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

Note Date is an instant in time, so it's default textual representation may vary from what you might expect. See the differences in lines 1 and 2 below,

1. Thu Jun 18 00:00:00 EDT 2015
2. 06/18/2015

Finally, you need to calculate the difference between two dates . compareTo will tell you smaller or bigger, not magnitude.

I made a method that takes in two dates, converts them and returns a long that works fine. 86400000 is the number of milliseconds in a day. I am using GregorianCalendar format

public long compareDates(Date exp, Date today){

         return (exp.getTime()-today.getTime())/86400000;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM