IAmYourFaja
IAmYourFaja

Reputation: 56894

Compare Joda LocalDateTime and DateTime within range

I'm trying to write a method that will take a LocalDateTime and a DateTime (using Joda 1.3) and determine if they are within 30 minutes of one another. Here's the best I can come up with, but I know there has to be a better/cleaner/more efficient way:

public boolean isWithin30MinsOfEachOther(LocalDateTime localDateTime, DateTime dateTime) {
    return (
        localDateTime.getYear() == dateTime.getYear() &&
        localDateTime.getMonthOfYear() == dateTime.getMonthOfYear() &&
        localDateTime.getDayOfMonth() == dateTime.getDayOfMonth() &&
        localDateTime.getHourOfDay() == dateTime.getHourOfDay() &&
        Math.abs((localDateTime.getMinuteOfHour() - dateTime.getMinuteOfHour())) <= 30
    );
)

Not to mention I don't think this works if, say, localDateTime is December 31, 2012 23:58:00 and dateTime is January 1, 2013 00:01:00. Same thing with the beginning/end of two different months and days. Any suggestions? Thanks in advance.

Upvotes: 0

Views: 981

Answers (2)

Tomas Narros
Tomas Narros

Reputation: 13468

Have you tried using the Duration class?

As an example:

  Duration myDuration=new Duration(localDateTime.toDateTime(), dateTime);
  return Math.abs(myDuration.getMillis())<=30*60*1000;

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

You could try

return Math.abs(localDateTime.getLocalMillis() 
                - dateTime.toLocalDateTime().getLocalMillis()) < 30 * 60 * 1000;

Upvotes: 0

Related Questions