Subtract JAVA dates from picking the days difference

Asked

Viewed 11,631 times

8

I need to calculate the day of pregnancy a woman is in, taking the information of the date when the woman became pregnant and the date of today.

I have the following instruction:

Date dtToday = new Date(); //pega a data de hoje
Data dtEngravidou = Mommy.getDtPregnantDate(); //retorna a data em que ficou grávida

In theory, I would need to subtract today’s date with the date of pregnancy and I would have the number of days that have passed, so I would have the difference, that is, how many days of pregnancy Mom is.

  • 2

    Your Date is a java.util.Date? Have you considered using a Jodatime?

  • It’s java.util.Date. I’ve never heard of this library, I’m new to the java world. You can post an answer as it would be using this Jodatime library?

2 answers

8


You can do this account using the classes Datetime and Duration of the Jodatime library.

import org.joda.time.DateTime;
import org.joda.time.Duration;

public class CalculaDiff {
    public static void main(String[] args) {
        DateTime dtToday = new DateTime(); //pega data e hora atual
        DateTime dtOther = new DateTime(DateTime.parse("2014-06-15T08:00:55Z")); //exemplo

        Duration dur = new Duration(dtOther, dtToday); //pega a duração da diferença dos dois

        System.out.println(dur.getStandardDays());
    }
}

Upshot:

16

You can download it here: Joda - Time

In that answer here has a good explanation of why not to use the standard libraries.

  • 1

    Perfect, in my case I needed for Android, there is a lib of it faster by not using the JAR that is this here link. However for solution purposes the Jodatime solved perfectly. Thanks.

2

Now, with the standard Java 8 Apis, you can do:

LocalDate dtToday = LocalDate().now();
LocalDate dtEngravidou = Mommy.getDtPregnantDate();
long diasDeGravidez = ChronoUnit.DAYS.between(dtEngravidou, dtToday);
System.out.println("Mamãe está grávida há " + diasDeGravidez + " dias");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.