Bevor
Bevor

Reputation: 8605

Java date calucation truncates decimal place at result

If I invoke this method with different dates, the decimal places of the result of difference / 1000L / 60L / 60L / 24L will always be truncated. What can I do to prevent that? I need a result of 4.xx.

public boolean checkDelayed(Date date1, Date date2)
{
    long difference = date2.getTime() - date1.getTime();

    if (difference / 1000L / 60L / 60L / 24L <= 4L)
    {
        return true;
    }

    return false;
}

Upvotes: 0

Views: 303

Answers (2)

Peter
Peter

Reputation: 3417

Instead of longs, you can also multiply instead of divide.

if (difference <= 4 * 1000 * 60 * 60 * 24 )
{
    return true;
}

Dividing is slower, and has a possibility of trimming off some numbers. Even dividing integers is slower than multiplying floats or doubles (in some cases? eg. AMD is best with floats, Intel with Integers). Using BigDecimal.divide(...) instead of double would prevent trimming but would be evern slower.

Multiplying's only disadvantage I can think of is that a really big number would overflow (ie. an calculated int could be larger than Integer.MAX_VALUE, or a long larger than Long.MAX_VALUE). But in your case, you only have constants, so it is the best choice.

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68887

Try using doubles instead of Longs.

public boolean checkDelayed(Date date1, Date date2)
{
    double difference = (double) (date2.getTime() - date1.getTime());

    if (difference / 1000d / 60d / 60d / 24d <= 4d)
    {
        return true;
    }

    return false;
}

The best way would be to apply simple math. Your condition is this:

difference / 1000L / 60L / 60L / 24L <= 4L

Work out like this:

        difference / 60L / 60L / 24L <= 4000L
              difference / 60L / 24L <= 240000L
                    difference / 24L <= 14400000L
                          difference <= 345600000L

There you have it. The always working simple condition.

public boolean checkDelayed(Date date1, Date date2)
{
    long difference = date2.getTime() - date1.getTime();

    if (difference <= 345600000L)
    {
        return true;
    }

    return false;
}

The reason for all of this is that the long datatype does not support decimal values. By converting to a double you will be able to keep the decimal values.

Upvotes: 3

Related Questions