Domanda

Having some trouble implementing this simple task.

Basically I want to compare two dates(some older date vs new date). I want to know if the older date is more than x months old and y days old.

int monthDiff = new Date().getMonth() - detail.getCdLastUpdate().getMonth();
int dayDiff = new Date().getDay() - detail.getCdLastUpdate().getMonth();
System.out.println("\tthe last update date and new date month diff is --> " + monthDiff);
System.out.println("\tthe last update date and new date day diff is --> " + dayDiff);

If older date is 2012-09-21 00:00:00.0, currently, it will return negative numbers. I need to find out if the older date is EXACTLY 6 months and 4 days before new Date(). I'm thinking of using absolute values of both but just can't brain today.

Edit: I know about joda but I cannot use it. I must use Java JDK. Edit 2: I'll try out the methods listed, if all failed I'll use Joda.

È stato utile?

Soluzione

JDK dates have before and after methods, returning boolean, to accomplish your task:

Date now = new Date();
Calendar compareTo = Calendar.getInstance();
compareTo.add(Calendar.MONTH, -6);
compareTo.add(Calendar.DATE, -4);
if (compareTo.getTime().before(now)) {
   // after
} else {
   // before or equal 
}

Altri suggerimenti

The best way I can think of is to use Joda-Time library. Example from their site:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Or number of months:

Months m = Months.monthsBetween(startDate, endDate)
int months = m.getMonths();

where:

DateTime startDate =  new DateTime(/*jdk Date*/);
DateTime endDate =  new DateTime(/*jdk Date*/);

Sigh, it is up to me to add the inevitable "use JodaTime" answer.

JodaTime gives you specific data types for all significant time distances.

Date yourReferenceDate = // get date from somewhere
int months = Months.monthsBetween(
                       new DateTime(yourReferenceDate),
                       DateTime.now()
             ).getMonths();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top